Presentation is loading. Please wait.

Presentation is loading. Please wait.

Inheritance Inheritance is a fundamental Object Oriented concept

Similar presentations


Presentation on theme: "Inheritance Inheritance is a fundamental Object Oriented concept"— Presentation transcript:

1 Inheritance Inheritance is a fundamental Object Oriented concept
A class can be defined as a "subclass" of another class. The subclass inherits all data attributes of its superclass The subclass inherits all methods of its superclass The subclass can: Add new functionality Use inherited functionality Override inherited functionality superclass: Person - name: String - dob: Date subclass: Employee - employeeID: int - salary: int - startDate: Date

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

3 What really happens? In this example, we can say that an Employee "is a kind of" Person. An Employee object inherits all of the attributes, methods and associations of Person Person name = "John Smith" dob = Jan 13, 1954 Person - name: String - dob: Date Employee name = "Sally Halls" dob = Mar 15, 1968 employeeID = 37518 salary = 65000 startDate = Dec 15, 2000 is a kind of Employee - employeeID: int - salary: int - startDate: Date

4 Inheritance in Java Inheritance is declared using the "extends" keyword If inheritance is not defined, the class extends a class called Object public class Person { private String name; private Date dob; [...] Person - name: String - dob: Date public class Employee extends Person { private int employeID; private int salary; private Date startDate; [...] Employee - employeeID: int - salary: int - startDate: Date Employee anEmployee = new Employee();

5 Types of Inheritance

6 Why Java doesn’t support multiple inheritance?
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.

7 Inheritance Hierarchy
Each Java class has one (and only one) superclass. C++ allows for multiple inheritance Inheritance creates a class hierarchy Classes higher in the hierarchy are more general and more abstract Classes lower in the hierarchy are more specific and concrete Class There is no limit to the number of subclasses a class can have There is no limit to the depth of the class tree. Class Class Class Class Class Class Class

8 The class called Object
At the very top of the inheritance tree is a class called Object All Java classes inherit from Object. The Object class is defined in the java.lang package Examine it in the Java API Specification Object

9 Constructors and Initialization
Classes use constructors to initialize instance variables When a subclass object is created, its constructor is called. It is the responsibility of the subclass constructor to invoke the appropriate superclass constructors so that the instance variables defined in the superclass are properly initialized Superclass constructors can be called using the "super" keyword in a manner similar to "this" It must be the first line of code in the constructor If a call to super is not made, the system will automatically attempt to invoke the no-argument constructor of the superclass.

10 Object References and Inheritance
A superclass reference can refer to an instance of the superclass OR an instance of ANY class which inherits from the superclass. BankAccount anAccount = new BankAccount(123456, "Craig"); BankAccount account1 = new OverdraftAccount(3323, "John", ); BankAccount name = "Craig" accountNumber = anAccount OverdraftAccount name = "John" accountNumber = 3323 limit = account1

11 super keyword 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.

12 Referring 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=“green";   }   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();   }}   Output: black green

13 super can be used to invoke parent class method
class Animal{   void eat(){System.out.println("eating Animal");}   }   class Dog extends Animal{   void eat(){System.out.println("eating bread");}   void bark(){System.out.println("barking");}   void work(){   super.eat();   bark();   class TestSuper2{   public static void main(String args[]){   Dog d=new Dog();   d.work();   }}   Output: eating Animal barking

14 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();   }}   Output: animal is created dog is created

15 Note: super() is added in each class constructor automatically by compiler if there is no super()
As we know well that default constructor is provided by compiler automatically if there is no constructor. But, it also adds super() as the first statement.

16 Final Methods and Final Classes
Methods can be qualified with the final modifier Final methods cannot be overridden. This can be useful for security purposes. public final boolean validatePassword(String username, String Password) { [...] Classes can be qualified with the final modifier The class cannot be extended This can be used to improve performance. Because there an be no subclasses, there will be no polymorphic overhead at runtime. public final class Color { [...]

17 Interface An interface in java is a blueprint of a class. Interfaces specify what a class must do and not how.  It is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface. But a class describes the attributes and behaviors of an object. And an interface contains behaviors that a class implements. An interface is similar to a class in the following ways − An interface can contain any number of methods. An interface is written in a file with a .java extension, with the name of the interface matching the name of the file. The byte code of an interface appears in a .class file.

18 Interface is different from class ----
We cannot instantiate an interface. An interface does not contain any constructors. All of the methods in an interface are unimplemented. An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final. An interface is not extended by a class; it is implemented by a class. An interface can extend multiple interfaces. Declaring Interfaces The interface keyword is used to declare an interface.  The Java compiler adds public and abstract keywords before the interface method. Moreover, it adds public, static and final keywords before data members.

19 Relationship between classes and interfaces

20 Output CSE UEM 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){   SBI b=new SBI();   System.out.println("ROI: "+b.rateOfInterest());   }}   interface myinterface{   void print();   }   class A implements  myinterface{   public void print() {System.out.println(“CSE UEM");}      public static void main(String args[]){   A obj = new A();   obj.print();    }   Output CSE UEM Output: ROI: 9.15

21 Multiple Inheritance in JAVA
interface I1{   void print();   }   interface I2{   void show();   class A implements I1, I2 {   public void print(){System.out.println("Hello");}   public void show(){System.out.println(“CSE");}      public static void main(String args[]){   A obj = new A();   obj.print();   obj.show();    }   Output: Hello CSE

22 Multiple inheritance is not supported through class in java, but it is possible by an interface, why? multiple inheritance is not supported in the case of class because of ambiguity. However, it is supported in case of an interface because there is no ambiguity. It is because its implementation is provided by the implementation class. As you can see in the above example, I1and I2 interface have same methods but its implementation is provided by class MyInterface, so there is no ambiguity. interface I1{   void print();   }   interface I2{     class MyInterface implements I1, I2{   public void print(){System.out.println("Hello");}   public static void main(String args[]){   MyInterface  obj = new  MyInterface();   obj.print();    }   Output: Hello

23 Interface inheritance
A class implements an interface, but one interface extends another interface. interface I1{   void print();   }   interface I2 extends I1{   void show();   class MyInterface implements I2{   public void print(){System.out.println("Hello");}   public void show(){System.out.println("Welcome");}      public static void main(String args[]){   MyInterface  obj = new  MyInterface();   obj.print();   obj.show();    }   } Output: Hello Welcome

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


Download ppt "Inheritance Inheritance is a fundamental Object Oriented concept"

Similar presentations


Ads by Google