Lecture 6

Week-6

  • Inheritance
  • Inheritance Basics
  • Types of inheritance
  • Using super
  • Method Overriding

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

  • 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

Rules for Java Method Overriding

  1. The method must have the same name as in the parent class
  2. The method must have the same parameter as in the parent class.

Understanding the problem without method overriding

Let’s understand the problem that we may face in the program if we don’t use method overriding.

  1. //Java Program to demonstrate why we need method overriding
  2. //Here, we are calling the method of parent class with child
  3. //class object.
  4. //Creating a parent class
  5. classVehicle{
  6. void run(){System.out.println(“Vehicle is running”);}
  7. }
  8. //Creating a child class
  9. classBike extends Vehicle{
  10. public static void main(String args[]){
  11. //creating an instance of child class
  12. Bike obj = new Bike();
  13. //calling the method with child class instance
  14. run();
  15. }
  16. }

 

OutputVehicle is running

Problem is that I have to provide a specific implementation of run() method in subclass that is why we use method overriding.

Example of method overriding

In this example, we have defined the run method in the subclass as defined in the parent class but it has some specific implementation. The name and parameter of the method are the same, and there is IS-A relationship between the classes, so there is method overriding.

  1. //Java Program to illustrate the use of Java Method Overriding
  2. //Creating a parent class.
  3. classVehicle{
  4. //defining a method
  5. void run(){System.out.println(“Vehicle is running”);}
  6. }
  7. //Creating a child class
  8. classBike2 extends Vehicle{
  9. //defining the same method as in the parent class
  10. void run(){System.out.println(“Bike is running safely”);}
  11. public static void main(String args[]){
  12. Bike2 obj = new Bike2();//creating object
  13. run();//calling method
  14. }
  15. }

Test it Now

Output:

Bike is running safely

Program

A real example of Java Method Overriding

Consider a scenario where Bank is a class that provides functionality to get the rate of interest. However, the rate of interest varies according to banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7%, and 9% rate of interest.

Java method overriding is mostly used in Runtime Polymorphism which we will learn in next pages.

  1. //Java Program to demonstrate the real scenario of Java Method Overriding
  2. //where three classes are overriding the method of a parent class.
  3. //Creating a parent class.
  4. classBank{
  5. intgetRateOfInterest(){return 0;}
  6. }
  7. //Creating child classes.
  8. classSBI extends Bank{
  9. intgetRateOfInterest(){return 8;}
  10. }
  11. classICICI extends Bank{
  12. intgetRateOfInterest(){return 7;}
  13. }
  14. classAXIS extends Bank{
  15. intgetRateOfInterest(){return 9;}
  16. }
  17. //Test class to create objects and call the methods
  18. classTest2{
  19. publicstatic void main(String args[]){
  20. SBI s=newSBI();
  21. ICICI i=newICICI();
  22. AXIS a=newAXIS();
  23. out.println(“SBI Rate of Interest: “+s.getRateOfInterest());
  24. out.println(“ICICI Rate of Interest: “+i.getRateOfInterest());
  25. out.println(“AXIS Rate of Interest: “+a.getRateOfInterest());
  26. }
  27. }

 

Test it Now

 

Output: SBI Rate of Interest: 8ICICI Rate of Interest: 7AXIS Rate of Interest: 9

Can we override static method?

No, a static method cannot be overridden. It can be proved by runtime polymorphism, so we will learn it later.

Why can we not override static method?

It is because the static method is bound with class whereas instance method is bound with an object. Static belongs to the class area, and an instance belongs to the heap area.

Can we override java main method?

No, because the main is a static method.

Inheritance

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 (Object Oriented programming system).

The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also.

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

  1. classSubclass-name extends Superclass-name
  2. {
  3. //methods and fields
  4. }

The extends keyword indicates that you are making a new class that derives from an existing class. The meaning of “extends” is to increase the functionality.

In the terminology of Java, a class which is inherited is called a parent or superclass, and the new class is called child or subclass.

 

Java Inheritance Example

As displayed in the above figure, 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.

  1. classEmployee{
  2. float salary=40000;
  3. }
  4. classProgrammer extends Employee{
  5. int bonus=10000;
  6. public static void main(String args[]){
  7. Programmer p=new Programmer();
  8. out.println(“Programmer salary is:”+p.salary);
  9. out.println(“Bonus of Programmer is:”+p.bonus);
  10. }
  11. }

Test it Now

 Programmer salary is:40000.0 Bonus of programmer is:10000

In the above example, Programmer object can access the field of own class as well as of Employee class i.e. code reusability.

Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface only. We will learn about interfaces later.

Note: Multiple inheritance is not supported in Java through class.

When one class inherits multiple classes, it is known as multiple inheritance. For Example:

Single Inheritance Example

File: TestInheritance.java

  1. classAnimal{
  2. voideat(){System.out.println(“eating…”);}
  3. }
  4. classDog extends Animal{
  5. voidbark(){System.out.println(“barking…”);}
  6. }
  7. classTestInheritance{
  8. publicstatic void main(String args[]){
  9. Dog d=newDog();
  10. bark();
  11. eat();
  12. }}

Output:

barking…eating…

Multilevel Inheritance Example

File: TestInheritance2.java

  1. classAnimal{
  2. voideat(){System.out.println(“eating…”);}
  3. }
  4. classDog extends Animal{
  5. voidbark(){System.out.println(“barking…”);}
  6. }
  7. classBabyDog extends Dog{
  8. voidweep(){System.out.println(“weeping…”);}
  9. }
  10. classTestInheritance2{
  11. publicstatic void main(String args[]){
  12. BabyDog d=newBabyDog();
  13. weep();
  14. bark();
  15. eat();
  16. }}

Output:

weeping…barking…eating…

 

Hierarchical Inheritance Example

File: TestInheritance3.java

  1. classAnimal{
  2. voideat(){System.out.println(“eating…”);}
  3. }
  4. classDog extends Animal{
  5. voidbark(){System.out.println(“barking…”);}
  6. }
  7. classCat extends Animal{
  8. voidmeow(){System.out.println(“meowing…”);}
  9. }
  10. classTestInheritance3{
  11. publicstatic void main(String args[]){
  12. Cat c=newCat();
  13. meow();
  14. eat();
  15. //c.bark();//C.T.Error
  16. }}

Output:

meowing…eating…

Q) Why multiple inheritance is not supported in java?

To reduce the complexity and simplify the language, multiple inheritance is not supported in java.

Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes have the same method and you 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.

  1. classA{
  2. voidmsg(){System.out.println(“Hello”);}
  3. }
  4. classB{
  5. voidmsg(){System.out.println(“Welcome”);}
  6. }
  7. classextends A,B{//suppose if it were
  8. public static void main(String args[]){
  9. C obj=new C();
  10. msg();//Now which msg() method would be invoked?
  11. }
  12. }

Test it Now

 Compile Time Error

Previous Lecture

Next Lecture

Lecture No

1     2     3     4     5     6     7     8     9     10     11     12     13     14     15

Please follow and like us:

Author: ilearnpoint

Leave a Reply

Your email address will not be published. Required fields are marked *