Inheritance
Inheritance Basics
• Java supports inheritance by allowing one class to incorporate another class
into its declaration. This is done by using the extends keyword.
• Thus , the subclass adds to(extends) the superclass.
Syntax:
class derived-class extends base-class
{
//methods and fields
}
The subclass B includes all of the members of its superclass, A. This is why
subOb can access i and j and call showij( ). Also, inside sum( ), i and j can be
referred to directly, as if they were part of B.
class A {
int i, j;
void showij()
{
System.out.println("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.
class B extends A {
class SimpleInheritance {
public static void main(String args[]) {
A superOb = new A();
B subOb = new B();
// The superclass may be used by itself.
superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println();
/* The subclass has access to all public members of its superclass. */
subOb.i = 7;
Member Access and Inheritance
Although a subclass includes all of the members of its superclass, it
cannot access those members of the superclass that have been
declared as private.
Member Access and Inheritance
Although a subclass includes all of the members of its superclass, it
cannot access those members of the superclass that have been
declared as private. For example, consider the following simple class
hierarchy:
This program will not compile because the reference to j inside the
sum( ) method of B causes an access violation. Since j is declared as
private, it is only accessible by other members of its own class.
Subclasses have no access to it.
Constructors and Inheritance
It is possible for both super classes and subclasses to have their own
constructors. The constructor for the superclass constructs the
superclass portion of the object, and the constructor for the subclass
constructs the subclass part.
Super Keyword in Java
The super keyword in java is a reference variable that is used to refer
parent class objects. The keyword “super” came into the picture with
the concept of Inheritance. It is majorly used in the following contexts:
Constructor and inheritance
Class TwoDShape
Private double width;
Private double height;
//Accessor method for width and height
Double getWidth() { return width;}
Double getHeight() { return height;}
Void setWidht(double w)
{ width = w; }
Void setHeight(double h)
{
Height = h;
}
void showDim()
{
System.out.println(“Widht and height are” + widht + “and” +height);
Class Triangle extends TwoDShape{
Constructor and inheritance
class Shape3 {
public static void main(String args[]) {
Triangle t1 = new Triangle(“filled “, 4.0, 4.0);
Triangle t2 = new Triangle(“outlined “, 8.0, 12.0);
System.out.println(“Info for t1: “):
t1 . showStyle();
t1. showDim();
System.out.println(“ Aea is “ +t1.area());
System.out.println(“Info for t2: “):
t2 . showStyle();
t2. showDim();
System.out.println(“ Aea is “ +t2.area());
}
}
1. Use of super with variables: This scenario occurs when a derived
class and base class has same data members. In that case there is a
possibility of ambiguity for the JVM.
2. Use of super with methods: This is used when we want to call
parent class method. So whenever a parent and child class have same
named methods then to resolve ambiguity we use super keyword.
3. Using super to Call Superclass constructors: uper keyword can also
be used to access the parent class constructor. One more important
thing is that, ‘’super’ can call both parametric as well as non parametric
constructors depending upon the situations.
Super Keyword in Java
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
• super can be used to refer immediate parent class instance variable.
• super can be used to invoke immediate parent class method.
• 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";
}
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
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}
super can be used to invoke parent class method
class Animal{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal{
void eat()
{
System.out.println("eating bread...");
}
void bark() {
System.out.println("barking...");
}
super is used to invoke parent class constructor.
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}
super example: real use
class Person{
int id;
String name;
Person(int id,String name){
this.id=id;
this.name=name;
}
}
class Emp extends Person{
float salary;
Emp(int id,String name,float salary)
{
super(id,name);//reusing parent constructor
Creating a Multilevel Hierarchy
In multilevel inheritance a sub class is derived from a derived class.
Each class inherits only a single class. Therefore, in multilevel
inheritance a ladder is formed which at each step increases by one and
the lowermost class will have the properties of all the super classes.
Order of execution of constructors in inheritance
Class A
{
A()
{
System.out.println(“constructing A.”); }
}
Class B extends A
{
B()
{
System.out.println(“constructing B.”); }}
Class C extends B
{
Method Overriding
In a class hierarchy, when a method in a subclass has the same name
and type signature as a method in its superclass, then the method in
the subclass is said to override the method in the superclass. When an
overridden method is called from within a subclass, it will always refer
to the version of that method defined by the subclass. The version of
the method defined by the superclass will be hidden.
Method overriding
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
void show() {
System.out.println("i and j: " + i + " " + j);
} }
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
// display k – this overrides show() in A
void show() {
System.out.println("k: " + k); } }
overridden methods polymorphism
class Sup
{
void who()
{
System.out.println("who() in Sup");
} }
class Sub1 extends Sup
{
void who()
{
System.out.println("who() in Sub1");
} }
class Sub2 extends Sup
{
void who()
{
System.out.println("who() in Sub2");
}
Abstract Class
Abstract Classes and Methods
Data abstraction is the process of hiding certain details and showing
only essential information to the user. Abstraction can be achieved with
either abstract classes or interfaces.
The abstract keyword is a non-access modifier, used for classes and
methods:
Abstract class: is a restricted class that cannot be used to create objects
(to access it, it must be inherited from another class).
Abstract method: can only be used in an abstract class, and it does not
have a body. The body is provided by the subclass (inherited from).
An abstract class can have both abstract and regular methods:
Abstract Class
Abstract class in Java
• A class that is declared as abstract is known as an abstract class. It can
have abstract and non-abstract methods. It needs to be extended and
its method implemented. It cannot be instantiated.
Points to Remember
• An abstract class must be declared with an abstract keyword.
• It can have abstract and non-abstract methods.
• It cannot be instantiated.
• It can have constructors and static methods also.
• It can have final methods which will force the subclass not to change
the body of the method.
• An abstract class can have a data member, abstract method, method
body (non-abstract method), constructor, and even main() method.
Abstract Class
abstract class Animal
{
// Abstract method (does not have a body)
public abstract void animalSound();
// Regular method
public void sleep()
{
System.out.println("Zzz");
}
}
// Subclass (inherit from Animal)
class Pig extends Animal
{
public void animalSound()
{
// The body of animalSound() is provided here
Abstract Class
abstract class Bike
{
Bike()
{
System.out.println("bike is created");
}
abstract void run();
void changeGear()
{
System.out.println("gear changed");}
}
//Creating a Child class which inherits Abstract class
Final Keyword In Java
The final keyword in java is used to restrict the user. The java final
keyword can be used in many context. Final can be:
variable
method
class
Java final variable
If you make any variable as final, you cannot change the value of final
variable(It will be constant).
class Bike9{
final int speedlimit=90; //final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}
Java final method
class Bike{
final void run(){System.out.println("running");}
}
class Honda extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
}
Java final class
final class Bike{}
class Honda1 extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda1 honda= new Honda1();
honda.run();
}
}