Java type casting - Inheritance

Converting one type of value to another is called as Type Casting.

Different Forms of Type Casting :

There are two types of type casting.
Type Casting - Different Forms

Live Example of Type Casting in Inheritance :

package com.c4learn.inheritance;
class Vehicle {
	String nameOfVehicle;	
}
class TwoWheeler extends Vehicle {
	String vehicleModel;	
}
public class TypeCastExample {
    public static void main(String[] args) {
    	Vehicle    v1 = new  Vehicle();
    	Vehicle    v2 = new  TwoWheeler();
    	TwoWheeler v3 = (TwoWheeler) new  Vehicle();
    	TwoWheeler v4 = new  TwoWheeler();
    }
}

A. Up Casting :

You can cast an instance of a child class to its parent class. Casting an object of child class to a parent class is called upcasting.

Consider the following example, Assuming that TwoWheeler is a subclass of Vehicle.

Vehicle    v2 = new  TwoWheeler();

B. Down Casting :

Casting an object of a parent class to its child class is called downcasting.

Consider the following example, Assuming that TwoWheeler is a subclass of Vehicle. Following is an example of the down casting -

TwoWheeler v3 = (TwoWheeler) new  Vehicle();

Java Interview Question #3 : Can Java have blank final Value ?

Que 3. Can Java have blank final Value ?

Answer : No

package com.c4learn.inheritance;
public class BlankFinalValue {
    final int myValue;
    public BlankFinalValue(){
    	this.myValue = 3;
    }
    public static void main(String[] args) {
    	BlankFinalValue s1 = new  BlankFinalValue();
    }
}

Output :

Compiler Successfully

Explanation :

  1. We cannot have final Value which is uninitialized.
  2. You will get compile time error if you did not provide initialization.
  3. In this case we have to provide initialization in the constructor. (As shown in above program)

If final variable is not initialized in the constructor then it will throw compile time error as below -

Uninitialized Final Value

If You have Multiple Constructor then -

we need to initialize final variable in each of the constructor like below program -

package com.c4learn.inheritance;
public class BlankFinalValue {
    final int myValue;
    public BlankFinalValue(){
    	this.myValue = 3;
    }
    public BlankFinalValue(int num){
    	this.myValue = num;
    }
    public static void main(String[] args) {
    	BlankFinalValue s1 = new  BlankFinalValue();
    }
}

If you failed to initialize final variable in any of the constructor then you will get compile time error -

The blank final field myValue may not have been initialized

Java Interview Question #2 : Can Java inherit Final Method ?

Que 2. Can we inherit Final Method ?

Answer : Yes

In case of final method, Method is inherited but cannot be overriden so always method from parent class will be executed.

Consider the following example -

package com.c4learn.inheritance;
public class ShapeClass {
    final void setShape() {
    	System.out.println("I am Inherited");;   	
    }
    public static void main(String[] args) {
    	Circle c1 = new  Circle();
    	c1.setShape();
    }
}
class Circle extends ShapeClass {
}

Output :

I am Inherited

We can inherit the final method but cannot override the final method inside the child class.

Java Interview Question #1 : Is Final Method more efficient in Java ?

Que 1. Final Vs Non Final Method, Which is more efficient ?

Answer : Final

  1. Final methods execute more efficiently than non final method.
  2. Compiler knows at compile time that a call to a final method won’t be overridden by some other method

Let’s See, How ?

Consider the final method,

package com.c4learn.inheritance;
public class ShapeClass {
    final void setShape() {
    	System.out.println("I am Inherited");;   	
    }
    public static void main(String[] args) {
    	Circle c1 = new  Circle();
    	c1.setShape();
    }
}
class Circle extends ShapeClass {
}

Whenever we create an object of the child class then compiler will check whether method written inside the parent class is overriden or not at run time.

final void setShape() {
    System.out.println("I am Inherited");;   	
}

In this case compiler already knows that, method is declared as final so it does not waste time in checking whether method is final or not.

Inheritance Questions : Interview Tips and Questions

We have just studied the final keyword and different usage of final keyword. In this chapter we have listed some of the frequently asked interview questions on the Final Keyword -

We have Listed Some of the frequently asked questions on Final Keyword -

Java final keyword

Final Keyword is used to stop user accessing the java variable or class or method. We can use final keyword in following three manner -

  1. Making Final Variable
  2. Making Final Method
  3. Making Final Class

Way 1 : Final Variable

If we make the variable final then the value of that variable cannot be changed once assigned. Consider the following example -

package com.c4learn.inheritance;
public class ShapeClass {
    final int SHAPE_SIDES = 3;
    void setShape() {
    	SHAPE_SIDES = 4;   	
    }
    public static void main(String[] args) {
    	ShapeClass c1 = new  ShapeClass();
    	c1.setShape();
    }
}

Output :

Compile Time Error

We cannot modify the value of the final variable, we will get following error message -

Cannot Modify Final Variable

Way 2 : Final Method

We cannot Override the final method as we cannot change the method once they are declared final. Consider the following example -

package com.c4learn.inheritance;
public class ShapeClass {
    int SHAPE_SIDES = 3;
    final void setShape() {
    	SHAPE_SIDES = 4;   	
    }
    public static void main(String[] args) {
    	ShapeClass c1 = new  ShapeClass();
    	c1.setShape();
    }
}
class Circle extends ShapeClass {
    void setShape() {    // Error Here
    	SHAPE_SIDES = 4;   	
    }	
}

Output :

Compile Time Error

In this example we have declared method as final so we cannot override the final method, otherwise we will get compile time error -

Cannot Override Final Method

Way 3 : Final Class

We cannot inherit the final class.

package com.c4learn.inheritance;
public final class ShapeClass {
    int SHAPE_SIDES = 3;
    final void setShape() {
    	SHAPE_SIDES = 4;   	
    }
    public static void main(String[] args) {
    	ShapeClass c1 = new  ShapeClass();
    	c1.setShape();
    }
}
class Circle extends ShapeClass { // Error Here
}

Output :

Compile Time Error

In this example we have declared class as final so we cannot inherit the final class

Cannot Inherite Final Class

Some Important Points : Final Keyword

  1. Final Keyword can be applied only on Method,Class and Variable
Final EntityDescription
Final ValueFinal Value cannot be modified
Final MethodFinal Method cannot be overriden
Final ClassFinal Class cannot be inherited
  1. Final Variable must be initialized at the time of declaration or inside constructor
  2. Re-Assigning Value is not allowed for final member variable
  3. Local Final Variable should be initialized during the time of declaration
  4. Final and Finally both are different. Finally keyword is used on Exception handling in Java

Java super keyword & constructors

Consider the following simple example of inheritance, We have created an object of child class -

Understanding Constructors :

package com.c4learn.inheritance;
public class ParentClass {
    public ParentClass()
    {
        System.out.println("Hello Parent");
    }
     public static void main(String[] args) {
	ChildClass c1 = new  ChildClass();
     }
}
class ChildClass extends ParentClass{
    public ChildClass()
    {
        System.out.println("Hello Child");
    }
}

Output of the Program :

Hello Parent
Hello Child

Explanation of above program :

When you create an instance of a child class, Java automatically calls the default constructor of the parent class before it executes the child class’s constructor. [ Also See - Constructor Example ]

Super Class - Default Constructor

Consider the following code -

package com.c4learn.inheritance;
public class ParentClass {
    public ParentClass()
    {
        System.out.println("Hello Parent");
    }
    public ParentClass(int val)
    {
        System.out.println("Hello Parameter");
    }
    public static void main(String[] args) {
        ChildClass c1 = new  ChildClass();
    }
}
class ChildClass extends ParentClass{
    public ChildClass()
    {
        super(5);
        System.out.println("Hello Child");
    }
}

Now In the above program, we have written two constructors one with no argument and another with single integer argument.

public ParentClass()
{
   System.out.println("Hello Parent");
}
public ParentClass(int val)
{
   System.out.println("Hello Parameter");
}

As we have explicitly called the single argument constructor using the super keyword, Parent Class’s Parameterized Constructor gets called.

Tip #1 : Super Must be First Statement

If you use super to call the parent class constructor, you must put it as first statement in the constructor.

Following is the valid way of calling parent class constructor -

public ChildClass()
{
   super(5);
   System.out.println("Hello Child");
}

If we write it after other statements then it will throw compile time error -

Super Class Constructor Error

Tip #2 : Default constructor

If you don’t explicitly call super, the compiler inserts a call to the default constructor of the base class. In that case, the base class must have a default constructor.

If the base class doesn’t have a default constructor, you will get compile time error.

Java super keyword

In the previous chapter of inheritance we have learnt about the different rules of method overriding, In this chapter we will be learning about the super keyword -

3 ways of Using Super Keyword :

Super is used to refer the immediate parent of the class. Whenever we create an object of the child class then the reference to the parent class will be created automatically.

We can user super keyword by using three ways -

  • Accessing Instance Variable of Parent Class
  • Accessing Parent Class Method
  • Accessing Parent Class Class Constructor

Way 1 : Accessing Instance Variable of Parent Class using Super

package com.c4learn.inheritance;
public class ParentClass {
    int ageClass = 100;
    public static void main(String[] args) {
        ChildClass c1 = new  ChildClass();
        c1.display();
    }
}
class ChildClass extends ParentClass{
    int ageClass = 200;
    public void display() {
	System.out.println("ageClass : " + ageClass);	
    }
}

Output of the Program

ageClass : 200

Consider the above example -

  1. We have same variable declared inside the parent class as well as in child class.
  2. Whenever we try to access the variable using the object of child class, always instance variable of child will be returned.

Suppose we want to access the the same variable from the parent class then we can modify the display() method as below -

public void display() {
     System.out.println("ageClass : " + super.ageClass);
}

Way 2 : Accessing Parent Class Method using Super

package com.c4learn.inheritance;
public class ParentClass {
    int ageClass = 100;
    public int getValue() {
    	return 20;
    }
    public static void main(String[] args) {
        ChildClass c1 = new  ChildClass();
        c1.display();        
    }
}
class ChildClass extends ParentClass{
    int ageClass = 200;
    public int getValue() {
    	return 50;
    }
    public void display() {
      System.out.println("result : " + super.getValue());
    }
}

Output :

result : 20

In this example we have same method declared inside parent and child class.

public void display() {
     System.out.println("result : " + super.getValue());
}

In order to execute the parent method from the child class we need to use super keyword.

Way 3 : Accessing Parent Class Constructor using Super

We will be learning super keyword and constructor in more details in the next chapter.

Java method overriding rules

In the previous topic we have seen Concept of Method Overriding.

1. Same Argument List :

The argument list should be exactly the same as that of the overridden method.

package com.c4learn.inheritance;
public class InheritanceRules {
    public int calculate(int num1,int num2) {
       return num1+num2;
    }
    public static void main(String[] args) {
       baseClass b1 = new baseClass();
       int result = b1.calculate(10, 10);
       System.out.println("Result : " + result);
    }
}
class baseClass extends InheritanceRules {
    public int calculate(int num1,int num2) {
       return num1*num2;
    }
}

In the above example, method is having the same set of parameter list -

public int calculate(int num1,int num2)

2. The return type :

Return type should be the same or a subtype of the return type declared in the Original Overridden method in the Parent Class.

Consider the following method from Parent Class -

public int calculate(int num1,int num2) {
    return num1+num2;
}

then we cannot change the return type of the method in the overriden method.

3. Modification of access level :

Access level cannot be lowerd down or restricted than the overridden method’s access level.

Suppose currently method in the Parent class is having the access level public then we cannot override the method with access level as private and protected.

below is the table which summarized the which are the allowed ways of modifing the access level of overriden method -

Access Level in ParentAccess Level in ChildAllowed ?
PublicPublicAllowed
PublicPrivateNot Allowed
PublicProtectedNot Allowed
ProtectedPublicAllowed
ProtectedProtectedAllowed
ProtectedPrivateNot Allowed

Following method will throw compile time error -

package com.c4learn.inheritance;
public class InheritanceRules {
    public int calculate(int num1,int num2) {
       return num1+num2;
    }
    public static void main(String[] args) {
       baseClass b1 = new baseClass();
       int result = b1.calculate(10, 10);
       System.out.println("Result : " + result);
    }
}
class baseClass extends InheritanceRules {
    private int calculate(int num1,int num2) {
       return num1*num2;
    }
}

because in the parent class, Method has Access level public while we have made access level as private in the child class.

4. Cannot Override Final Methods :

We cannot override the final method declared in the Parent Class/Super Class. Consider the following method is written inside the Parent Class -

final public int calculate(int num1,int num2) {
    return num1+num2;
}

5. Cannot Override Static Methods but Re-declaration is possible :

Consider the following method declared inside the Parent Class -

public static int calculate(int num1,int num2) {
    return num1+num2;
}

then child class cannot override static method from parent class but it can redeclare it just by changing the method body like this -

public static int calculate(int num1,int num2) {
    return num1*num2;
}

however we have to keep the method static in the child class, we cannot make it non-static in the child class, So following method declaration inside child class will throw error -

public int calculate(int num1,int num2) { //without static
    return num1*num2;
}

6. Rule for Methods that Cannot be Inherited :

If a method cannot be inherited, then it cannot be overridden by the child class. We cannot inherite the private methods of the parent class in the child class. So private methods cannot be overriden by the childe class. However redeclaration of private method is possible in the child method -

public class InheritanceRules {
    private int calculate(int num1,int num2) {
       return num1+num2;
    }
}
class baseClass extends InheritanceRules {
    private int calculate(int num1,int num2) {
       return num1*num2;
    }
}

7. Constructors cannot be overridden :

Java method overriding

If a method is declared in the parent class and method with same name and parameter list is written inside the subclass then it is called method overriding.

Rules for Method Overriding :

  1. Method Must have Same Name as that of Method Declared in Parent Class
  2. Method Must have Same Parameter List as that of Method Declared in Parent Class
  3. IS-A relation should be maintained in order to Override Method.

Why we need to override method ?

Consider the following Parent Class -

class Human {
   void talk() {
      System.out.println("Talking Human");
   }
}

Conside following child class -

class Male extends Human {
    public static void main(String args[]) {
	   Male m1 = new Male();
	   m1.talk();	
	}
}

We want to provide the different implementation to talk() method for Male and Human class. Using override we can provide different implementations for talk() in Parent Class and in Child Class.

Method Overriding Example :

Vehicle.java

package com.c4learn.inheritance;
public class Vehicle {
   public void vehicleMethod() {
     System.out.println("Method in Vehicle.");
   }
}

TwoWheeler.java

package com.c4learn.inheritance;
public class TwoWheeler extends Vehicle {
    public void vehicleMethod() {
        System.out.println("Method" + " in TwoWheeler.");
    }
    public static void main(String[] args) {
        TwoWheeler myBike = new TwoWheeler();
        Vehicle myVehicle = new Vehicle();
        myVehicle.vehicleMethod();
        myBike.vehicleMethod();
    }
}

Output of the Program :

Method in Vehicle.
Method in TwoWheeler.