0% found this document useful (0 votes)
33 views41 pages

Inheritance in Java

Uploaded by

Dr. Neetu Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
33 views41 pages

Inheritance in Java

Uploaded by

Dr. Neetu Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 41

INHERITANCE

IN
JAVA
INHERITANCE
 In Java, one class can easily inherit the attributes and
methods from some other class. This mechanism of
acquiring objects and properties from some other class
is known as inheritance in Java.
 Inheritance is used to borrow properties & methods
from an existing class.
 Inheritance helps us create classes based on existing
classes, which increases the code's reusability.
Important terminologies used in Inheritance :
1.Parent class/superclass: The class from which a class inherits
methods and attributes is known as parent class.
2.Child class/sub-class: The class that inherits some other class's
methods and attributes is known as child class.
Extends keyword in inheritance :
The extends keyword is used to inherit a subclass
from a superclass.
Syntax :
class Subclass-name extends Superclass-name
{
//methods and fields
}
Example :
public class dog extends Animal {
// code
}
Types of inheritance in Java.
 JAVA CLASS DOES NOT SUPPORT MULTIPLE INHERITANCE
Why multiple inheritance is not
supported in Java class?

 The reason behind this is to prevent ambiguity.


 Consider a case where class B extends class A and Class C
and both class A and C have the same method display().
 Now java compiler cannot decide, which display method it
should inherit. To prevent such situation, multiple
inheritances is not allowed in java.
 Due to such a problem, java does not support multiple
inheritance directly, but the similar concept can be
achieved using interfaces.
 A class can implement multiple interfaces and extend a
class at the same time.
package com.company;
class Base{
public int x;
public int getX() {
return x;
}
public void setX(int x) {
System.out.println("I am in base and setting x now");
this.x = x;
}
public void printMe(){
System.out.println("I am a constructor");
}}
class Derived extends Base{
public int y;
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}}
public class Main {
public static void main(String[] args) {
// Creating an Object of base class
Base b = new Base();
b.setX(4);
System.out.println(b.getX());
// Creating an object of derived class
Derived d = new Derived();
d.setY(43);
System.out.println(d.getY());
}
}
this keyword in Java
 this can be used to refer current class instance
variable.
 this keyword eliminates the confusion between the
parameters and the class attributes with the same
name.
THIS CODE CONTAINS LOGICAL ERROR
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
rollno=rollno;
name=name;
fee=fee;
}
void display(){System.out.println(rollno+" “
+name+" "+fee);}
}
class TestThis1{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
 In the above example, parameters (formal
arguments) and instance variables are
same. So, we are using this keyword to
distinguish local variable and instance
variable.
 If local variables(formal arguments) and
instance variables are different, there is no
need to use this keyword.
 It is better approach to use meaningful
names for variables. So we use same name
for instance variables and parameters in
real time, and always use this keyword.
With
packagethis
com.company;
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+"
"+fee);}
}
class Main{
public static void main(String args[]){
Student s1=new
Student(111,"ankit",5000f);
Student s2=new
Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
Constructors in Inheritance
When a derived class is extended from the
base class, the constructor of the base class is
executed first followed by the constructor of
the derived class. For the following Inheritance
hierarchy , the constructors are executed in
the order:
 C1- Parent
 C2 - Child
 C3 - Grandchild
Constructors during constructor
overloading
 When there are multiple constructors in the
parent class, the constructor without any
parameters is called from the child class.
 If we want to call the constructor with
parameters from the parent class, we can use
the super keyword.
 super(a, b) calls the constructor from the
parent class which takes 2 variables
package com.company;
class Base1{
Base1(){
System.out.println("I am a constructor");
}
Base1(int x){
System.out.println("I am an overloaded
constructor with value of x as: " + x);
}}
class Derived1 extends Base1{
Derived1(){
System.out.println("I am a derived
class constructor");
}
Derived1(int x, int y){
super(x);
System.out.println("I am an overloaded
constructor of Derived with value of y as: " + y);
}}
class ChildOfDerived extends Derived1{
ChildOfDerived(){
System.out.println("I am a child of derived
constructor");
}
ChildOfDerived(int x, int y, int z){
super(x, y);
System.out.println("I am an overloaded
constructor of Derived with value of z as: " + z);
}}
public class Main {
public static void main(String[] args)
{
ChildOfDerived cd = new
ChildOfDerived(12, 13, 15);
}
}
Super keyword
A reference variable used to
refer immediate parent class
object.
It can be used to refer
immediate parent class
instance variable.
It can be used to invoke the
parent class method.
FINAL
Abstract Class & Abstract Methods
 Abstract in English means existing in through or as an idea without concrete
existence.
Abstract class :
 An abstract class cannot be instantiated.
 Java requires us to extend it if we want to
access it.
 It can include abstract and non-abstract
methods.
 If a class includes abstract methods, then the
class itself must be declared abstract.
 Abstract class are used when we want to
achieve security & abstraction(hide certain
details & show only necessary details to the
user)
package com.company;
import javax.print.Doc;
abstract class Phone{
abstract void on();
}
class SmartPhone extends Phone {
void on() {
System.out.println("Turning on...");
}}
class Main{p
public static void main(String args[]){
Phone obj = new SmartPhone();
obj.on();
}}
abstract class Bank{
abstract int getRateOfInterest();
}
class SBI extends Bank{
int getRateOfInterest(){return 7;}
}
class PNB extends Bank{
int getRateOfInterest(){return 8;}
}
class TestBank{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
b=new PNB();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
}}
Abstract method :
A method that is declared without
implementation is known as the abstract
method.
 An abstract method can only be used
inside an abstract class.
 The body of the abstract method is
provided by the class that inherits the
abstract class in which the abstract
method is present.
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
class Honda extends Bike{
void run(){System.out.println("running safely..");}
}
//Creating a Test class which calls abstract and non-abstract methods
class TestAbstraction2{
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
obj.changeGear();
} }
INTERFACE

 Just like a class in java is a collection of the related methods, an interface in


java is a collection of abstract methods.
 The interface is one more way to achieve abstraction in Java.
 An interface may also contain constants, default methods, and static
methods.
 All the methods inside an interface must have empty bodies except default
methods and static methods.
 We use the interface keyword to declare an interface.
 There is no need to write abstract keyword before declaring methods in an
interface because an interface is implicitly abstract.
 An interface cannot contain a constructor (as it cannot be used to create
objects)
 In order to implement an interface, java requires a class to use
the implement keyword.
SYNTAX-INTERFACE
interface <interface_name>{

// declare constant fields


// declare methods that abstract
// by default.
}
Interface fields are public, static and final by default,
and the methods are public and abstract.
Example of interface
interface Bank{
float rateOfInterest();
}
class SBI implements Bank{
public float rateOfInterest(){return 9.15f;}
}
class PNB implements Bank{
public float rateOfInterest(){return 9.7f;}
}
class TestInterface2{
public static void main(String[] args){
Bank b=new SBI();
Multiple inheritance using Java
Interface
interface Printable{
void print();
}
interface Showable{
void show(); }
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
A7 obj = new A7();
obj.print();
obj.show();
} }
Will not ambiguity problem arise?

How Can Interface supports Multiple


Inheritance while Java classes cannot?
DIFFERENCE BETWEEN ABSTRACT CLASS AND INTERFACE.
Abstract class achieves partial abstraction (0 to
100%) whereas interface achieves fully abstraction
(100%).
Abstract class Interface

1) Abstract class can have abstract and non- Interface can have only abstract methods. Since Java 8,
abstract methods. it can have default and static methods also.
2) Abstract class doesn't support multiple Interface supports multiple inheritance.
inheritance.
3) Abstract class can have final, non-final, static and Interface has only static and final variables.
non-static variables.
4) Abstract class can provide the implementation of Interface can't provide the implementation of abstract
interface. class.
5) The abstract keyword is used to declare abstract The interface keyword is used to declare interface.
class.
6) An abstract class can extend another Java class An interface can extend another Java interface only.
and implement Java interfaces.
7) An abstract class can be extended using keyword An interface can be implemented using keyword
"extends". "implements".
8) A Java abstract class can have class members like Members of a Java interface are public by default.
private, protected, etc.

You might also like