Professional Documents
Culture Documents
MODULE 3
Inheritance in Java is a mechanism in which one object
acquires all the properties and behaviors of a parent object.
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 you are
making a new class that derives from an existing
class.
EXAMPLE
class A{
int a=10;
int b=10;
}
class B extends A{
int j=12;
}
class inheritance{
public static void main(String args[]){
B p=new B();
System.out.println(“a ,b and c is:"+p.a+””+p.b+””+p.c);
}
}
Types of inheritance in java
Single inheritance
Multilevel inheritance
Heirarchical
Java does not support multiple and hybrid
inheritance
subclass cannot access those members of the
superclass that have been declared as private.
SUPER
class RefDemo {
public static void main(String args[]) {
BoxWeight weightbox = new BoxWeight(3, 5, 7, 8.37);
Box plainbox = new Box();
double vol;
vol = weightbox.volume();
System.out.println("Volume of weightbox is " + vol);
System.out.println("Weight of weightbox is " +
weightbox.weight);
System.out.println();
// assign BoxWeight reference to Box reference
plainbox = weightbox;
vol = plainbox.volume(); // OK, volume() defined in Box
System.out.println("Volume of plainbox is " + vol);
/* The following statement is invalid because plainbox
does not define a weight member. */
// System.out.println("Weight of plainbox is " + plainbox.weight);
}
}
METHOD OVERRIDING