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

Inheritance

JAVA CONCEPT

Uploaded by

AK FREEZE
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views

Inheritance

JAVA CONCEPT

Uploaded by

AK FREEZE
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 35

Inheritance

Adapted from
www.cs.utep.edu/vladik/cs2
401.10a/Ch_11_Inheritance
_Polymorphism.ppt

1
Review: Classes
• User-defined data types
• Defined using the “class” keyword
• Each class has associated
• Data members (any object type)
• Methods that operate on the data
• New instances of the class are declared using the “new” keyword
• “Static” members/methods have only one copy for a class,
regardless of how many instances are created
Example: Shared Functionality
public class Student { public class Professor {
String name; String name;
char gender; char gender;
Date birthday; Date birthday;

double getGPA() {
… int getCiteCount() {
} …
}
int getAge(Date today) {
… int getAge(Date today) {
} …
} }
}
public class Person {
String name;
char gender;
Date birthday;

int getAge(Date today) {



}
}

public class Student public class Professor


extends extends Person {
Person {

int getCiteCount() {
double getGPA() { …
… }
} }
}
Definiton:
• Inheritance is a mechanism in which one object acquires all the
properties and behaviors of a parent object. It is an important part
of OOPs (Object Oriented programming system).

• Need: The idea is to create new classes that are built upon existing
classes.
• Inheriting from an existing class, shall allow reuse of methods and
fields of the parent class.
• Moreover, new methods and fields can be added in current class
also.

5
IS-A relationship
• Inheritance represents the IS-A relationship which is also known
as a parent-child relationship.

6
Benefits of inheritance
• For Method Overriding (so runtime polymorphism can be
achieved).
• For Code Reusability.

7
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.
8
The syntax of Java Inheritance
class Subclass- class Employee
name extends Superclass {  
-name    float salary=40000;  
}  
{   class Programmer extends Employee
   //methods and fields   {  
 int bonus=10000;  
}    public static void main(String args[])
{  
   Programmer p=new Programmer();  
   System.out.println("Programmer salary 
is:"+p.salary);  
   System.out.println("Bonus of Program
mer is:"+p.bonus);  
}  

9
Types of Inheritance
• Single inheritance: class Animal
{  
• Subclass / Derived class is void eat()
derived from one existing {System.out.println("eating...");}  
class (superclass / Base }  
class) class Dog extends Animal
{  
void bark()
{System.out.println("barking...");}  
Base Class }  
A class TestInheritance
{  
Derived Class public static void main(String args[]{
B Dog d=new Dog();  
d.bark();  
d.eat();  
}}  
Multi-Level inheritance:
Class B inherits class A. class Animal
Class C inherits class B {  
void eat()
{
System.out.println("eating...");}  
}  
class Dog extends Animal
Base Class {  
A void bark()
{System.out.println("barking...");}  
Derived Class
B
}  
class BabyDog extends Dog
Derived Class {  
C void weep()
{System.out.println("weeping...");}  
}  

11
Multilevel inheritance contd..
class TestInheritance2
{  
public static void main(String args[])
{  
BabyDog d=new BabyDog();  
d.weep();  
d.bark();  
d.eat();  
}
}  

12
Inheritance
• Multiple inheritance:
• Subclass is derived from more than one superclass
• Not supported by Java

Base Class Base Class


A B

Not supported
Derived
Class
Access Modifiers
• The access modifiers in Java specifies the accessibility or scope of a
field, method, constructor, or class. We can change the access level of
fields, constructors, methods, and class by applying the access
modifier on it.
Modifier Class Package Outside Outside
Package Package
by
Subclass
public Y Y Y Y

protected Y Y Y N

none Y Y N N

private Y N N N
UML Diagram: Rectangle

What if we want to implement a 3d box object?

Remember: - Private Member


+ Public Member
Objects myRectangle and myBox
Rectangle myRectangle = new Rectangle(5, 3);
Box myBox = new Box(6, 5, 4);
UML Class Diagram: class Box

Both a Rectangle and a Box have a surface area,


but they are computed differently
Note: Private data members of Rectangle Note: Both Box and Rectangle classes have
cannot be directly accessed by Box objects. common methods names.
They can only be accessed by public methods. Different signature (setDimension)
E.g. length can be accessed by getLength() Same signature (area)
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.

18
Why do we need method overriding

• Method overriding is used to provide the specific implementation


of a method which is already provided by its superclass.

• Method overriding is used for runtime polymorphism

19
20
Why do we need method
overriding???
//Here, we are calling the method of parent class with child  
//class object. Creating a parent class  
class Vehicle Problem is that you have to
{   provide a specific
implementation of run()
  void run() method in subclass that is why
{ we use method overriding.
System.out.println("Vehicle is running");
}}   Output:
//Creating a child class   Vehicle is running
class Bike extends Vehicle{  
  public static void main(String args[]){  
  //creating an instance of child class  
  Bike obj = new Bike();  
  //calling the method with child class instance  
  obj.run();  
  } } 
21
Overriding Methods (When subclass
and super class have same functions
(including signatures)
• A subclass can override (redefine) the methods of the superclass

• Objects of the subclass type will use the new method


• Objects of the superclass type will use the original
Program to illustrate the use of 
Java Method Overriding 
 
//Creating a parent class.     {System.out.println("Bike is ru
class Vehicle nning safely");
{  
}  public static void main(Strin
  //defining a method  
  void run() g args[])
{System.out.println("Vehicle is ru {  
nning");   Bike2 obj = new Bike2();//
}}   creating object  
//Creating a child class     obj.run();//calling method  
class Bike2 extends Vehicle   }  
{   }
  // Output:
defining the same method as in th Bike is running safely
e parent class  
  void run()
23
final keyword
• It is used to restrict the user.

• It can be used in three contexts:

I. Variable
II.Method
III.Class

24
Use of final

25
Example of final variable
class Bike9
{   There is a final variable
speedlimit, we are going to
 final int speedlimit=90;//final variable  
change the value of this
 void run(){   variable, but It can't be
  speedlimit=400;   changed because final
 }   variable once assigned a value
can never be changed.
 public static void main(String args[]){  
 Bike9 obj=new  Bike9();  
 obj.run();  
 }   Output:
}//end of class   Compile Time error

26
Example of 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[]){   If you make any
method as final, you
   Honda honda= new Honda();   cannot override it.
   honda.run();  
Output:
   }   Compile Time error

27
Example of 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();   If you make any class
as final, you cannot
  honda.run();   extend it.
  }  
Output:
} Compile Time error

28
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.

29
30
super is used to refer immediate
parent class instance variable.
class Animal{  
String color="white";   We can use super keyword to
}   access the data member or field
class Dog extends Animal{   of parent class. It is used if
String color="black";   parent class and child class
void printColor(){   have same fields.Animal and
System.out.println(color);// Dog both classes have a
prints color of Dog class  
System.out.println(super.color);// common property color. If we
prints color of Animal class   print color property, it will
}  }   print the color of current class
class TestSuper1{   by default. To access the parent
public static void main(String args[]) property, we need to use super
{ keyword.
Dog d=new Dog();  
Output:
d.printColor();   black
}} white
31
super can be used to invoke parent
class method
class Animal{  
void eat() class TestSuper2{  
{System.out.println("eating...");}   public static void main(String a
}  
rgs[]){  
class Dog extends Animal{  
void eat() Dog d=new Dog();  
{System.out.println("eating bread. d.work();  
..");}   }} 
void bark()
{System.out.println("barking..."); Output:
}   eating...
void work(){   barking...
super.eat();  
bark();  
}  
Animal and Dog both classes have eat() method if we call eat() method from
}  
Dog class, it will call the eat() method of Dog class by default because priority is
given to local. To call parent class we are using super keyword.
32
super can be used to invoke parent
class constructor
class Animal{    class TestSuper3{  
Animal() public static void main(String a
{System.out.println("animal is cre rgs[]){  
ated");}  
Dog d=new Dog();  
}  
}}  
class Dog extends Animal{  
Dog(){   Output:
super();   animal is created
System.out.println("dog is created") dog is created
;  
}  

Note: super() is added in each class constructor automatically by compiler if
there is no super() or this().
33
Calling methods of the superclass
• If subclass overrides public method of superclass, call to
public method of superclass is made as follows:
super.MethodName(parameter list)

• If subclass does not override public method of superclass,


call to public method of superclass is made as follows:
MethodName(parameter list)

34
Defining Constructors of the Subclass
Call to constructor of superclass:
 Must be first statement
 Specified by super parameter list
 in a class hierarchy, constructors are called in order of
derivation, from superclass to subclass

public Box() public Box(double l,


{ double w, double h)
super(); {
height = super(l, w);
0; height = h;
} }

35

You might also like