0% found this document useful (0 votes)
13 views

JavaChap3 Inheritance

Inheritance in Java allows one class to inherit properties and behaviors from another class, promoting code reusability and establishing a hierarchical relationship. It supports various types of inheritance such as single, multilevel, and hierarchical, while multiple inheritance is achieved through interfaces to avoid ambiguity. The document also discusses the use of the 'super' keyword, method overriding, and the concept of abstract classes in Java.

Uploaded by

01fe23bca218
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

JavaChap3 Inheritance

Inheritance in Java allows one class to inherit properties and behaviors from another class, promoting code reusability and establishing a hierarchical relationship. It supports various types of inheritance such as single, multilevel, and hierarchical, while multiple inheritance is achieved through interfaces to avoid ambiguity. The document also discusses the use of the 'super' keyword, method overriding, and the concept of abstract classes in Java.

Uploaded by

01fe23bca218
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 49

Inheritance in Java

Chapter 3
Introduction
• Inheritance in Java is a mechanism in which one object acquires all
the properties and behaviors of a parent object.
• It is an important part of OOPs
• The idea behind inheritance in Java is that we can
create new classes that are built upon existing classes
• When we inherit methods from an existing class, we can
reuse methods and fields of the parent class.
• However, we can add new methods and fields in your
current class also
What is Inheritance?

• Inheritance in Java enables a class to inherit properties


and actions from another class, called a superclass or
parent class
• A class derived from a superclass is called a subclass or
child group
• Through inheritance, a subclass can access members of its superclass
(fields and methods), enforce reuse rules, and encourage hierarchy.
• Inheritance represents the IS-A relationship which is also
known as a parent-child relationship
Why use inheritance in Java?

• For Method Overriding (so runtime polymorphism can


be achieved).
• For Code Reusability.
Terms used in Inheritance
• Class: A class is a group of objects which have common
properties. It is a template or blueprint from which objects are
created.
• Sub Class/Child Class: Subclass is a class which inherits the
other class. It is also called a derived class, extended class, or
child class.
• Super Class/Parent Class: Superclass is the class from where
a subclass inherits the features. It is also called a base class or
a parent class.
• Reusability: As the name specifies, reusability is a mechanism
which facilitates you to reuse the fields and methods of the
existing class when you create a new class. You can use the
same fields and methods already defined in the previous class.
The syntax of Java Inheritance

class Subclass-name extends Superclass-name


{
//methods and fields
}
• The extends keyword indicates that we are making a
new class that derives from an existing class.
• The meaning of "extends" is to increase the
functionality.
Java Inheritance Example

• Programmer is the subclass and Employee is the


superclass.
• The relationship between the two classes
is Programmer IS-A Employee.
• It means that Programmer is a type of Employee.
Types of Inheritance in Java
Multiple inheritance is not supported in
Java through class
• When one class inherits multiple classes, it is known as multiple
inheritance.
• Why multiple inheritance is not supported in Java?
• To reduce the complexity and simplify the language,
multiple inheritance is not supported in java.
• Suppose there are three classes A, B, and C. The C class inherits A and B
classes. If A and B classes have the same method and we call it from
child class object, there will be ambiguity to call the method of A or B
class.
• Since compile-time errors are better than runtime errors, Java renders
compile-time error if you inherit 2 classes. So whether you have same
method or different, there will be compile time error.
Problem with multiple inheritance
C.java

class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
//suppose if it were
class C extends A,B{
public static void main(String args[]){
C obj=new C();
obj.msg(); //Now which msg() method would be invoked?
}
}
How to achieve Multiple Inheritance in Java?

• Java supports multiple inheritance through interfaces


only, where a class can implement multiple interfaces.
• Multiple inheritance in Java is not possible by class, but
it is possible through interfaces.
Advantages of Inheritance
• Code Reusability: Inherited members from a superclass
can be reused in subclasses, reducing redundant code and
promoting a modular approach to software development.
• Hierarchical Organization: Inheritance facilitates the
creation of well-structured class hierarchies, improving code
readability and maintainability.
• Polymorphism: Subclasses can override superclass
methods, allowing for polymorphic behavior, where methods
can behave differently based on the object type at runtime.
• Easier Maintenance: Changes made to a superclass
automatically propagate to its subclasses, ensuring
consistency and simplifying maintenance efforts.
Single Inheritance
• When a class inherits another class, it is known as a single inheritance
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}

public class Main{


public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Multilevel Inheritance
• When there is a chain of inheritance, it is known as multilevel inheritance

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
public class Main{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Hierarchical Inheritance
• When two or more classes inherits a single class, it is known as hierarchical inheritance.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
public class Main{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Super Keyword

• The super keyword in Java is a reference variable which is


used to refer immediate parent class object.
• Whenever you create the instance of subclass, an instance
of parent class is created implicitly which is referred by
super reference variable.
• Usage of Java super Keyword
1.super can be used to refer immediate parent class instance
variable.
2.super can be used to invoke immediate parent class
method.
3.super() can be used to invoke immediate parent class
constructor.
super is used to refer immediate parent class instance variable.
• We can use super keyword to access the data member or field of parent class.
• It is used if parent class and child class have same fields.
class Animal{
String color="white";
}
//Creating child class
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
//Creating Main class to create object and call methods
public class Main{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}
super can be used to invoke parent class method

• The super keyword can also be used to invoke parent


class method.
• It should be used if subclass contains the same method
as parent class.
• In other words, it is used if method is overridden
class Animal{
void eat(){System.out.println("eating...");}
}
//Creating child class
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
void bark(){System.out.println("barking...");}
void work(){
super.eat();
bark();
}
}
//Creating Main class to create object and call methods
public class Main{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}
}
super is used to invoke parent class constructor
• The super keyword can also be used to invoke the parent class constructor. Let’s see a
simple example:
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super(); //calls the constructor of parent class
System.out.println("dog is created");
}
}
public class Main{
public static void main(String args[]){
Dog d=new Dog();
}
}
super vs this
• super() is added in each class constructor automatically
by compiler if there is no super() or this().
• As we know well that default constructor is provided by
compiler automatically if there is no constructor.
• But, it also adds super() as the first statement.
Another example of super keyword where super() is
provided by the compiler implicitly.
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
System.out.println("dog is created");
}
}
public class Main{
public static void main(String args[]){
Dog d=new Dog();
}
}

OUTPUT :
animal is created
dog is created
Superclass References and Subclass Objects

How to Refer a subclass object ?


• There are two approaches to refer a subclass object.
• Both have some advantages/disadvantages over the other.
• The declaration affect is seen on methods that are visible at
compile-time.
1. First approach (Referencing using Superclass reference):
• A reference variable of a superclass can be used to a refer any subclass
object derived from that superclass.
• If the methods are present in SuperClass, but overridden by SubClass, it
will be the overridden method that will be executed.
2. Second approach (Referencing using subclass
reference) :
• A subclass reference can be used to refer its object.
3. Static method in java could not be overridden
Superclass References and Subclass Objects

• Why Use This?


o Polymorphism: Lets you use superclass references to handle multiple
subclass objects, making code more flexible.
o Abstraction: Hides implementation details while exposing only necessary
methods.
o Loose Coupling: Reduces dependency between classes, making the code
easier to maintain.
Key Points
Method Overriding: The subclass method gets called (runtime polymorphism)
if overridden
Accessing Subclass-Specific Methods:
You cannot call subclass-specific methods directly using a superclass reference:
Examples :
class Parent {
public void parentPrint() {
System.out.println("parent print called");
}
public static void staticMethod() {
System.out.println("parent static method called");
}
}
Example :
public class SubclassReference extends Parent {
public void parentPrint() {
System.out.println("child print called");
}
public static void staticMethod() {
System.out.println("child static method called");
}
public static void main(String[] args) {
//SubclassReference invalid = new Parent();//Type mismatch: cannot convert from Parent to SubclassReference
Parent obj = new SubclassReference();
obj.parentPrint(); //method of subclass would execute as subclass object at runtime.
obj.staticMethod(); //method of superclass would execute as reference of superclass. (static method in java could not be
overridden)
Parent obj1 = new Parent();
obj1.parentPrint(); //method of superclass would execute as superclass object at runtime.
obj1.staticMethod(); //method of superclass would execute as reference of superclass.
SubclassReference obj3 = new SubclassReference();
obj3.parentPrint(); //method of subclass would execute as subclass object at runtime.
obj3.staticMethod(); //method of subclass would execute as reference of subclass.
}
Method Overriding
• If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java.
• In other words, If a subclass provides the specific implementation of the method
that has been declared by one of its parent class, it is known as method
overriding.

Usage of Java Method Overriding


1.Method overriding is used to provide the specific implementation of a method that
is already provided by its superclass.
2.Method overriding is used for runtime polymorphism.
3.Method overriding allows subclasses to reuse and build upon the functionality
provided by their superclass, reducing redundancy and promoting modular code
design.
4.Subclasses can override methods to tailor them to their specific needs or to
implement specialized behavior that is unique to the subclass.
5.Method overriding enables dynamic method dispatch, where the actual method
implementation to be executed is determined at runtime based on the type of
object, supporting flexibility and polymorphic behavior
Method Overriding - Rules
• Same Method Name:
• The overriding method in the subclass must have the same name as the method in
the superclass that it is overriding.
• Same Parameters:
• The overriding method must have the same number and types of parameters as
the method in the superclass.
• This ensures compatibility and consistency with the method signature defined in
the superclass.
• IS-A Relationship (Inheritance):
• Method overriding requires an IS-A relationship between the subclass and the
superclass.
• This means that the subclass must inherit from the superclass, either directly or
indirectly, to override its methods.
• Same Return Type or Covariant Return Type:
• The return type of the overriding method can be the same as the return type of
the overridden method in the superclass, or it can be a subtype of the return type
in the superclass.
• This is known as the covariant return type, introduced in Java 5.
Method Overriding - Rules
• Access Modifier Restrictions:
• The access modifier of the overriding method must be the same as or
• less restrictive than the access modifier of the overridden method in the superclass.
• Specifically, a method declared as public in the superclass can be overridden as public or
protected but not as private.
• Similarly, a method declared as protected in the superclass can be overridden as
protected or public but not as private.
• A method declared as default (package-private) in the superclass can be overridden with
default, protected, or public, but not as private.
• No Final Methods:
• Methods declared as final in the superclass cannot be overridden in the subclass.
• This is because final methods cannot be modified or extended .
• No Static Methods:
• Static methods in Java are resolved at compile time and cannot be overridden.
• Instead, they are hidden in the subclass if a method with the same signature is defined in
the subclass.
• When you define a static method with the same signature as a static method in the base
class, it is known as method hiding.
Method Overriding – Example 1
class Animal {
// Base class
void move() { System.out.println("Animal is moving."); }
void eat() { System.out.println("Animal is eating."); }
}
class Dog extends Animal {
// move method from Base class is overriden in this method
@Override
void move() {
System.out.println("Dog is running.");
}
void bark() { System.out.println("Dog is barking."); }
}
Method Overriding – Example 1 (contd)
public class Geeks {
public static void main(String[] args)
{
Dog d = new Dog();
d.move(); // Output: Dog is running.
d.eat(); // Output: Animal is eating.
d.bark(); // Output: Dog is barking.
}
}
Method Overriding – Example 2
class Parent {
// base class or superclass which is going to overriden
// below
void show() { System.out.println("Parent's show()"); }
}
// Inherited class
class Child extends Parent {
// This method overrides show() of Parent
@Override void show()
{
System.out.println("Child's show()");
}
}
Method Overriding – Example 2 (contd)
// Driver class
class Method_Over {
public static void main(String[] args)
{
// If a Parent type reference refers to a Parent object, then Parent's show is called

Parent obj1 = new Parent();


obj1.show();

// If a Parent type reference refers to a Child object, Child's show() is called. This is called RUN TIME
POLYMORPHISM.

Parent obj2 = new Child();


obj2.show();
}
}
Abstract class and inheritance
• An abstract is a Java non access modifier applicable for classes and
methods in Java but not for Variables
What is Abstract Class in Java?
• Java abstract class is a class that cannot be instantiated by itself, it
needs to be subclassed by another class to use its properties.
• An abstract class is declared using the “abstract” keyword in its
class definition.
• Example :
abstract class Shape
{
int color;
abstract void draw(); // An abstract function
}
Important observations about abstract
classes
1.An instance of an abstract class cannot be created.
2.Constructors are allowed.
3.We can have an abstract class without any abstract method.
4.There can be a final method in abstract class but any abstract method in
class(abstract class) can not be declared as final or in simpler terms final method
can not be abstract itself as it will yield an error: “Illegal combination of modifiers:
abstract and final”
5.We can define static methods in an abstract class
6.We can use the abstract keyword for declaring top-level classes (Outer
class) as well as inner classes as abstract
7.If a class contains at least one abstract method then compulsory should
declare a class as abstract
8.If the Child class is unable to provide implementation to all abstract methods of
the Parent class then we should declare that Child class as abstract so that
the next level Child class should provide implementation to the remaining abstract
method
Example of Abstract Class that has Abstract method
// Abstract class
abstract class Sunstar {
class Test {
abstract void printInfo(); public static void main(String args[])
} {
// Abstraction performed using extends Sunstar s = new Employee();
class Employee extends Sunstar { s.printInfo();
void printInfo() }
}
{
String name = "avinash";
int age = 21;
float salary = 222.2F;

System.out.println(name);
System.out.println(age);
System.out.println(salary);
}
}
Abstract Class having constructor, data member,
and methods
An abstract class can have
• data member
• abstract method
• method body (non-abstract method)
• constructor
• main() method.
abstract class Subject {
//constructor
Subject() {
System.out.println("Learning Subject");
}
//Abstract method
abstract void syllabus();
//non abstract method
void Learn(){
System.out.println("Preparing Right Now!");
}
}
class IT extends Subject {
void syllabus(){
System.out.println("C , Java , C++");
}
}

class Test {
public static void main(String[] args) {
Subject x=new IT();

x.syllabus();
x.Learn();
}
}
using final
• The final Keyword in Java is used as a non-access modifier applicable only to
a variable, a method, or a class.
• It is used to restrict a user in Java.
The following are different contexts where the final is
used:
1.Variable 🡪 Used to create Constant variable
2.Method 🡪 Used to prevent method overriding
3.Class 🡪 Used to prevent inheritance or subclassing
using final 🡪 Prevent Overriding
abstract class Shape // getHeight method is declared as final so any class extending
{ Shape can not override it
private double width; public final double getHeight()
{
private double height; return height;
// Shape class parameterized constructor }

public Shape(double width, double height) // method getArea() declared abstract because it upon its
{ subclasses to provide complete implementation
abstract double getArea();
this.width = width; }
this.height = height;
}
// getWidth method is declared as final so
any class extending Shape can't override it
public final double getWidth()
{
return width;
class Rectangle extends Shape //derived class two
{ class Square extends Shape
// Rectangle class parameterized constructor {
public Rectangle(double width, double height) // Square class parameterized constructor
{ public Square(double side)
// calling Shape class constructor {
super(width, height); // calling Shape class constructor
} super(side, side);
}
// getArea method is overridden and declared
// as final so any class extending Rectangle can't // getArea method is overridden and declared as
override it // final so any class extending
@Override // Square can't override it
final double getArea() @Override
{ final double getArea()
return this.getHeight() * this.getWidth(); {
} return this.getHeight() * this.getWidth();
}
}
}
// Driver class
public class Test
{
public static void main(String[] args)
{
// creating Rectangle object
Shape s1 = new Rectangle(10, 20);

// creating Square object


Shape s2 = new Square(10);

// getting width and height of s1


System.out.println("width of s1 : "+ s1.getWidth());
System.out.println("height of s1 : "+ s1.getHeight());
// getting width and height of s2
System.out.println("width of s2 : "+ s2.getWidth());
System.out.println("height of s2 : "+ s2.getHeight());

//getting area of s1
System.out.println("area of s1 : "+ s1.getArea());

//getting area of s2
System.out.println("area of s2 : "+ s2.getArea());

}
}
using final 🡪 Prevent Inheritance
final class FinalClass {
void display(){
System.out.println(“Inside FinalClass");
}
}

// This will cause a compilation error since FinalClass cannot be extended


class SubClass extends FinalClass { }
using final 🡪 with Data members
• Final variables:
• When a variable is declared as final, its value cannot be changed once it
has been initialized.
• essentially, a constant
• This is useful for declaring constants or other values that should not be
modified.
• Final variables must be initialized either at the time of declaration or in
the constructor of the class.
• This ensures that the value of the variable is set and cannot be changed.
• If the final variable is a reference, this means that the variable cannot
be re-bound to reference another object, but the internal state of the
object pointed by that reference variable can be changed.
• It is good practice to represent final variables in all uppercase, using
underscore to separate words.
Object Class
• The Object class is the parent class of all the classes in java
by default.
• In other words, it is the topmost class of java.
• The Object class is beneficial if you want to refer any object
whose type you don't know.
Methods of Object class
Method Description

public final Class getClass() returns the Class class object of this object.
The Class class can further be used to get
the metadata of this class.

public int hashCode() returns the hashcode number for this


object.
public boolean equals(Object obj) compares the given object to this object.

protected Object clone() throws creates and returns the exact copy (clone)
CloneNotSupportedException of this object.

public String toString() returns the string representation of this


object.
public final void notify() wakes up single thread, waiting on this
object's monitor.

public final void notifyAll() wakes up all the threads, waiting on this
object's monitor.
Methods of Object class
Method Description

public final void wait(long timeout)throws causes the current thread to wait for the
InterruptedException specified milliseconds, until another thread
notifies (invokes notify() or notifyAll()
method).
public final void wait(long timeout,int causes the current thread to wait for the
nanos)throws InterruptedException specified milliseconds and nanoseconds,
until another thread notifies (invokes
notify() or notifyAll() method).
public final void wait()throws causes the current thread to wait, until
InterruptedException another thread notifies (invokes notify() or
notifyAll() method).
protected void finalize()throws Throwable is invoked by the garbage collector before
object is being garbage collected.

You might also like