Java Programming Manish Kumar (manish87it@gmail.com) Lecture- 6
Contents  Introduction to Inheritance  Importance of Inheritance & Sample code  Types of Inheritance  Aggregation in java  Method Overriding  Rules for Method Overriding  Constructor in Inheritance  Static and Dynamic Binding
inheritance  Inheritance is a mechanism in java by which one class object is allow to inherit the features i.e. fields & methods of another class object.  The class whose features are inherited is called parent/base/super class and the class that inherits the features is called child/sub/derived class.  Inheritance in java represents the IS-A relationship which is also called parent-child relationship.  We used extends keyword to inherit the features of a class. Following is the syntax of extends keyword: class Child-class extends Parent-class { // methods; } Importance of Inheritance Method Overriding – We can achieved run-time polymorphism Code Reusability – Inheritance support the concept Reusability, i.e. you can reuse the fields & methods of the existing class into new created class.
Sample Code class Employee{ float salary=40000; } class Developer extends Employee{ int bonus=10000; public static void main(String args[]){ Developer d=new Developer (); System.out.println("Programmer salary is:"+d.salary); System.out.println("Bonus of Programmer is:"+d.bonus); } } Output - Programmer salary is: 40000.0 Bonus of programmer is: 10000 Employee.java In this code, Developer object can access the field of own class as well as of Employee class, i.e. code reusability. As we seeing in this code, Developer is the child class and Employee is the parent class. The relationship between the classes is Developer IS-A Employee. It means that Developer is a type of Employee.
Types of inheritance Single Inheritance Multilevel Inheritance Hierarchal Inheritance Multiple Inheritance Hybrid Inheritance
Single inheritance In single inheritance, one sub-class and one-super- class. Super-class Sub-class // Test.java class Demo { void display() { System.out.println(“Sparsh Globe”); } } class Test extends Demo { public static void main(String args[]) { Demo d = new Demo(); d.display(); } } Output - Sparsh Globe In this example, we can see that Test class inherit the features of Demo class, so there is a single inheritance.
Multilevel inheritance When there is a chain of inheritance is called Multilevel Inheritance, i.e. when a derived class act as the parent class to other class. //Main.java class First { void show1() { System.out.println(“S. Globe”); } } Class Second extends First { void show2() { System.out.println(“Sparsh Globe”); } } class Third extends Second { void show3() { System.out.println(“Third Class”); } } class Main { public static void main(String args[]) { Third t = new Third(); t.show1(); t.show2(); t.show3(); } } Output - S. Globe Sparsh Globe Third Class A B C
Hierarchal inheritance A single class can inherited by two or more than two class, known as Hierarchal Inheritance. A AAA // Test.java class First { void show1() { System.out.println("S. Globe"); } } class Second extends First { void show2() { System.out.println("Sparsh Globe"); } } class Third extends First { void show3() { System.out.println("Third Class"); } } class Test { public static void main(String args[]) { Third t = new Third(); t.show1(); t.show3(); Second s = new Second(); s.show2(); } } Output - S. Globe Third Class Sparsh Globe
Multiple inheritance In this, there are two or more than two parent class exist. That is, one subclass can have two or more than two parent class. Multiple Inheritance does not supported in java. A C B In Java, we can achieve multiple inheritance only through interfaces. To reduce the complexity, multiple inheritance does not support in java.
Multiple & hybrid inheritance Multiple inheritance is not supported in java. Let’s understand this with a scenario as discussed below: For Example - 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. Hybrid Inheritance - It is a mix of two or more of the above types of inheritance. Since java doesn’t support multiple inheritance with classes, the hybrid inheritance is also not possible with classes. In java, we can achieve hybrid inheritance only through Interfaces.
aggregation Aggregation represents HAS-A relationship and if a class have an entity reference, it is known as Aggregation. Let’s consider an example; suppose a Circle object contains one more object named Operation, which contains its operation like square, area, etc. Example – class Circle { double pi = 3.14; Operation op; // Operation is a class } In such case Circle has an entity reference op, so relationship is Circle HAS-A op.
Aggregation (contd..) Aggregation is used for Code Reusability. Inheritance should be used only if the relationship is-a is maintained throughout the lifetime of the objects involved; otherwise, aggregation is the best choice. Example - //Address.java public class Address { String city,state,country; public Address(String city, String state, String country) { this.city = city; this.state = state; this.country = country; } }
aggregation //Emp.java public class Emp { int id; String name; Address address; public Emp(int id, String name,Address address) { this.id = id; this.name = name; this.address=address; } void display(){ System.out.println(id+" "+name); System.out.println(address.city+" "+address.state+" " +address.country); } public static void main(String[] args) { Address address1=new Address("KNP","UP","india"); Address address2=new Address("LKO","UP","india"); Emp e=new Emp(101,"Manish",address1); Emp e2=new Emp(102,"Sparsh",address2); e.display(); e2.display(); } } Output – 101 Manish KNP UP India 102 Sparsh LKO UP India
Method overriding Overriding is a concept in which a sub-class to provide a specific implementation of a method that is already provided by one of its super-class. In this concept, sub-class has a method with same name, parameter/signature and return type as contains in super-class. In this case we say that method of sub-class override the method of super-class. We can achieve Run Time Polymorphism, with the help Method Overriding. //Circle.java class Polygon { public void area() { System.out.println(“Area of Polygon is calculated”); } } class Circle extends Polygon { public void area() { System.out.println(“Area of Circle is calculated”); } public static void main(String args[]) { // If a parent type reference refers to child object Polygon p = new Circle(); // circle’s area() is called. This is called Run Time Polymorphism. p.area(); } } Output- Area of Circle is calculated
Rules for method overriding 1. Overriding and Access-Modifiers: To understand this, first we know about access-modifiers. So, In short we discuss here access-modifiers later see in detail. Access Modifier within class within package outside package by subclass only outside package Private Y N N N Default Y Y N N Protected Y Y Y N Public Y Y Y Y A default/protected/private method (defined in child-class) can’t be overriding the public method (defined in parent-class) but vice-versa is true.
1-Overriding and access modifiers // Test.java class First { public void show1() { System.out.println("S. Globe"); } } class Second extends First { void show1() { System.out.println("Sparsh Globe"); } } class Test { public static void main(String args[]) { Second t = new Second(); t.show1(); } } Output – error: show1() in Second cannot override show1() in First void show1() { ^ attempting to assign weaker access privileges; was public
2-Overriding and Final If we declare a method as final in java, it means that we cannot override this method. //FinalMethod.java class First { final void show1() { System.out.println("Final Method"); } } class Second extends First { void show1() { System.out.println("Sparsh Globe"); } } class FinalMethod { public static void main(String args[]) { Second t = new Second(); t.show1(); } } Output – error: show1() in Second cannot override show1() in First void show1() { ^ overridden method is final
3-Overriding and static method In the case static method, it will execute like overriding but this concept is not called overriding because of not achieving Run-Time Polymorphism. Hence the answer is – we cannot override the static method. This concept is known as Method Hiding. A static method cannot be overridden by an instance method and an instance method cannot be hidden by static method. class First { //StaticMethod.java static void show1() { System.out.println("Final Method"); } } class Second extends First { void show1() { System.out.println("Sparsh Globe"); } } class StaticMethod { public static void main(String args[]) { Second t = new Second(); t.show1(); } } Output – Sparsh Globe
4 & 5 - Private 4. Private methods cannot be overridden due to bonded during compile time. 5.We cannot override the method if we change the return type of both the method before JDK 5.0 but in advanced version of JDK it possible to override with different return type with few conditions: i. A method must have a return-type of type current class – type. ii. Method must return current class object.
4 & 5 - Private Example – (Test.java) – This concept is called covariant return type. class First { First show1() { System.out.println("Final Method"); return new First(); } } class Second extends First { Second show1() { System.out.println("Sparsh Globe"); return new Second(); } } class Test { public static void main(String args[]) { Second t = new Second(); t.show1(); } } Output – Sparsh Globe
Constructor in inheritance In java, constructor in inheritance operates in different way i.e. un-parameterized constructor of base class gets automatically called in child-class constructor. Example – (ConstructorInInheritance.java) class First { First() { System.out.println("Base class"); } } class Second extends First { Second() { System.out.println("Child class"); } } class ConstructorInInheritance { public static void main(String args[]) { new Second(); } } Output - Base class Child class
Constructor in inheritance But if we want to call parameterized constructor defined in base class, then we must use super() method but remember this method must be the first line in child-class constructor. Example – (ConstructorInInheritance.java) class First { First(int x) { System.out.println("Base class - "+x); } } class Second extends First { Second() { Super(10); System.out.println("Child class"); } } class ConstructorInInheritance { public static void main(String args[]) { new Second(); } } Output - Base class - 10 Child class Note – Constructors are never being inherited.
Static binding Static binding is also known as Early Binding. If the type of object is determined by the compiler, then it is known as Static Binding. If any class has private, final or static method, it means there is static binding. Example – (StaticBinding.java) class StaticBinding { private void show() { System.out.println("static binding"); } public static void main(String args[]) { StaticBinding sb = new StaticBinding (); sb.show(); } } Output – static binding
dynamic binding If the type of object is determined at run-time then it is known as Dynamic Binding. It is also known as Late Binding. Example – (DynamicBinding.java) class Polygon { void area(){ System.out.println("Area of Polygon"); } } class Circle extends Polygon { void area(){ System.out.println("Area of Circle"); } } class Test { public static void main(String args[]){ Polygon p=new Circle(); p.area(); } } Output – Area of Circle
Lecture 6 inheritance

Lecture 6 inheritance

  • 1.
  • 2.
    Contents  Introduction toInheritance  Importance of Inheritance & Sample code  Types of Inheritance  Aggregation in java  Method Overriding  Rules for Method Overriding  Constructor in Inheritance  Static and Dynamic Binding
  • 3.
    inheritance  Inheritance isa mechanism in java by which one class object is allow to inherit the features i.e. fields & methods of another class object.  The class whose features are inherited is called parent/base/super class and the class that inherits the features is called child/sub/derived class.  Inheritance in java represents the IS-A relationship which is also called parent-child relationship.  We used extends keyword to inherit the features of a class. Following is the syntax of extends keyword: class Child-class extends Parent-class { // methods; } Importance of Inheritance Method Overriding – We can achieved run-time polymorphism Code Reusability – Inheritance support the concept Reusability, i.e. you can reuse the fields & methods of the existing class into new created class.
  • 4.
    Sample Code class Employee{ floatsalary=40000; } class Developer extends Employee{ int bonus=10000; public static void main(String args[]){ Developer d=new Developer (); System.out.println("Programmer salary is:"+d.salary); System.out.println("Bonus of Programmer is:"+d.bonus); } } Output - Programmer salary is: 40000.0 Bonus of programmer is: 10000 Employee.java In this code, Developer object can access the field of own class as well as of Employee class, i.e. code reusability. As we seeing in this code, Developer is the child class and Employee is the parent class. The relationship between the classes is Developer IS-A Employee. It means that Developer is a type of Employee.
  • 5.
  • 6.
    Single inheritance In singleinheritance, one sub-class and one-super- class. Super-class Sub-class // Test.java class Demo { void display() { System.out.println(“Sparsh Globe”); } } class Test extends Demo { public static void main(String args[]) { Demo d = new Demo(); d.display(); } } Output - Sparsh Globe In this example, we can see that Test class inherit the features of Demo class, so there is a single inheritance.
  • 7.
    Multilevel inheritance When thereis a chain of inheritance is called Multilevel Inheritance, i.e. when a derived class act as the parent class to other class. //Main.java class First { void show1() { System.out.println(“S. Globe”); } } Class Second extends First { void show2() { System.out.println(“Sparsh Globe”); } } class Third extends Second { void show3() { System.out.println(“Third Class”); } } class Main { public static void main(String args[]) { Third t = new Third(); t.show1(); t.show2(); t.show3(); } } Output - S. Globe Sparsh Globe Third Class A B C
  • 8.
    Hierarchal inheritance A singleclass can inherited by two or more than two class, known as Hierarchal Inheritance. A AAA // Test.java class First { void show1() { System.out.println("S. Globe"); } } class Second extends First { void show2() { System.out.println("Sparsh Globe"); } } class Third extends First { void show3() { System.out.println("Third Class"); } } class Test { public static void main(String args[]) { Third t = new Third(); t.show1(); t.show3(); Second s = new Second(); s.show2(); } } Output - S. Globe Third Class Sparsh Globe
  • 9.
    Multiple inheritance In this,there are two or more than two parent class exist. That is, one subclass can have two or more than two parent class. Multiple Inheritance does not supported in java. A C B In Java, we can achieve multiple inheritance only through interfaces. To reduce the complexity, multiple inheritance does not support in java.
  • 10.
    Multiple & hybridinheritance Multiple inheritance is not supported in java. Let’s understand this with a scenario as discussed below: For Example - 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. Hybrid Inheritance - It is a mix of two or more of the above types of inheritance. Since java doesn’t support multiple inheritance with classes, the hybrid inheritance is also not possible with classes. In java, we can achieve hybrid inheritance only through Interfaces.
  • 11.
    aggregation Aggregation represents HAS-Arelationship and if a class have an entity reference, it is known as Aggregation. Let’s consider an example; suppose a Circle object contains one more object named Operation, which contains its operation like square, area, etc. Example – class Circle { double pi = 3.14; Operation op; // Operation is a class } In such case Circle has an entity reference op, so relationship is Circle HAS-A op.
  • 12.
    Aggregation (contd..) Aggregation isused for Code Reusability. Inheritance should be used only if the relationship is-a is maintained throughout the lifetime of the objects involved; otherwise, aggregation is the best choice. Example - //Address.java public class Address { String city,state,country; public Address(String city, String state, String country) { this.city = city; this.state = state; this.country = country; } }
  • 13.
    aggregation //Emp.java public class Emp{ int id; String name; Address address; public Emp(int id, String name,Address address) { this.id = id; this.name = name; this.address=address; } void display(){ System.out.println(id+" "+name); System.out.println(address.city+" "+address.state+" " +address.country); } public static void main(String[] args) { Address address1=new Address("KNP","UP","india"); Address address2=new Address("LKO","UP","india"); Emp e=new Emp(101,"Manish",address1); Emp e2=new Emp(102,"Sparsh",address2); e.display(); e2.display(); } } Output – 101 Manish KNP UP India 102 Sparsh LKO UP India
  • 14.
    Method overriding Overriding isa concept in which a sub-class to provide a specific implementation of a method that is already provided by one of its super-class. In this concept, sub-class has a method with same name, parameter/signature and return type as contains in super-class. In this case we say that method of sub-class override the method of super-class. We can achieve Run Time Polymorphism, with the help Method Overriding. //Circle.java class Polygon { public void area() { System.out.println(“Area of Polygon is calculated”); } } class Circle extends Polygon { public void area() { System.out.println(“Area of Circle is calculated”); } public static void main(String args[]) { // If a parent type reference refers to child object Polygon p = new Circle(); // circle’s area() is called. This is called Run Time Polymorphism. p.area(); } } Output- Area of Circle is calculated
  • 15.
    Rules for methodoverriding 1. Overriding and Access-Modifiers: To understand this, first we know about access-modifiers. So, In short we discuss here access-modifiers later see in detail. Access Modifier within class within package outside package by subclass only outside package Private Y N N N Default Y Y N N Protected Y Y Y N Public Y Y Y Y A default/protected/private method (defined in child-class) can’t be overriding the public method (defined in parent-class) but vice-versa is true.
  • 16.
    1-Overriding and accessmodifiers // Test.java class First { public void show1() { System.out.println("S. Globe"); } } class Second extends First { void show1() { System.out.println("Sparsh Globe"); } } class Test { public static void main(String args[]) { Second t = new Second(); t.show1(); } } Output – error: show1() in Second cannot override show1() in First void show1() { ^ attempting to assign weaker access privileges; was public
  • 17.
    2-Overriding and Final Ifwe declare a method as final in java, it means that we cannot override this method. //FinalMethod.java class First { final void show1() { System.out.println("Final Method"); } } class Second extends First { void show1() { System.out.println("Sparsh Globe"); } } class FinalMethod { public static void main(String args[]) { Second t = new Second(); t.show1(); } } Output – error: show1() in Second cannot override show1() in First void show1() { ^ overridden method is final
  • 18.
    3-Overriding and staticmethod In the case static method, it will execute like overriding but this concept is not called overriding because of not achieving Run-Time Polymorphism. Hence the answer is – we cannot override the static method. This concept is known as Method Hiding. A static method cannot be overridden by an instance method and an instance method cannot be hidden by static method. class First { //StaticMethod.java static void show1() { System.out.println("Final Method"); } } class Second extends First { void show1() { System.out.println("Sparsh Globe"); } } class StaticMethod { public static void main(String args[]) { Second t = new Second(); t.show1(); } } Output – Sparsh Globe
  • 19.
    4 & 5- Private 4. Private methods cannot be overridden due to bonded during compile time. 5.We cannot override the method if we change the return type of both the method before JDK 5.0 but in advanced version of JDK it possible to override with different return type with few conditions: i. A method must have a return-type of type current class – type. ii. Method must return current class object.
  • 20.
    4 & 5- Private Example – (Test.java) – This concept is called covariant return type. class First { First show1() { System.out.println("Final Method"); return new First(); } } class Second extends First { Second show1() { System.out.println("Sparsh Globe"); return new Second(); } } class Test { public static void main(String args[]) { Second t = new Second(); t.show1(); } } Output – Sparsh Globe
  • 21.
    Constructor in inheritance Injava, constructor in inheritance operates in different way i.e. un-parameterized constructor of base class gets automatically called in child-class constructor. Example – (ConstructorInInheritance.java) class First { First() { System.out.println("Base class"); } } class Second extends First { Second() { System.out.println("Child class"); } } class ConstructorInInheritance { public static void main(String args[]) { new Second(); } } Output - Base class Child class
  • 22.
    Constructor in inheritance Butif we want to call parameterized constructor defined in base class, then we must use super() method but remember this method must be the first line in child-class constructor. Example – (ConstructorInInheritance.java) class First { First(int x) { System.out.println("Base class - "+x); } } class Second extends First { Second() { Super(10); System.out.println("Child class"); } } class ConstructorInInheritance { public static void main(String args[]) { new Second(); } } Output - Base class - 10 Child class Note – Constructors are never being inherited.
  • 23.
    Static binding Static bindingis also known as Early Binding. If the type of object is determined by the compiler, then it is known as Static Binding. If any class has private, final or static method, it means there is static binding. Example – (StaticBinding.java) class StaticBinding { private void show() { System.out.println("static binding"); } public static void main(String args[]) { StaticBinding sb = new StaticBinding (); sb.show(); } } Output – static binding
  • 24.
    dynamic binding If thetype of object is determined at run-time then it is known as Dynamic Binding. It is also known as Late Binding. Example – (DynamicBinding.java) class Polygon { void area(){ System.out.println("Area of Polygon"); } } class Circle extends Polygon { void area(){ System.out.println("Area of Circle"); } } class Test { public static void main(String args[]){ Polygon p=new Circle(); p.area(); } } Output – Area of Circle