Inheritance Java – Create object to subclass, but not to superclass ?
This tutorial explains the reason for Inheritance in Java, why we create an object to subclass, but not to super class. Deriving new classes by extending the existing classes so that the new classes will have all the features of existing classes is called inheritance.
Inheritance – Why we don’t create an object to superclass
First, let us see what happens when we create an object to super class in the following example.
class Super { void method1(){ System.out.println("In Super"); } } class Sub extends Super { void method2(){ System.out.println("In Sub"); } } class Cast { public static void main(String args[]){ Sub sub; //sub -> sub class reference sub= (Sub)new Super(); //sub refer to super class object sub.method1(); } }
Output
Exception in thread "main" java.lang.ClassCastException: Super cannot be cast to Sub
From the above response, it is evident that method call sub.method1() which is super class method and is not getting executed. Similarly when you try to call sub.method2() which is sub class method, this will also result in same error. Therefore we cannot access any of the methods of super class or sub class.
So the programmer will get 0% functionality access. The solution to this problem is to instead of creating an object to super class you need to create an object to sub class.
Inheritance – Why we create an object to subclass ?
To understand why we create an object to subclass, but not to super class, let’s try to run the following program. In this example, we are going to create super class reference to refer to sub class object as shown.
class Super { void method1(){ System.out.println("In Super"); } } class Sub extends Super { void method2(){ System.out.println("In Sub"); } } class Cast { public static void main(String args[]){ Super sup; //sup -> super class reference //create an object to sub class sup = new Sub(); //sup -> super class reference refer to sub class object Sub sub = (Sub)sup; // narrowing - convert super class reference //access super class and sub class methods - 100% functionality access sub.method1(); sub.method2(); } }
Output
In Super In Sub
It is evident that if we create super class reference to refer to the object of sub class, then it is possible to access all the methods of super class and sub class. This is the reason why we create an object always to sub class in Java Inheritance.
Also See:
- Explicit Type Casting Examples Java Primitives and Class Objects
- Declare and initialize arrays in Java Programming
- Java 8 : Find union and intersection of two Lists (ArrayLists)
- Convert List to Map in Java 8 using Streams and Collectors
- Selection Sort in Java and Complexity Analysis
- Java : How to Compare two Sets and check its Equality efficiently