How to convert a sub class variable into a super class type in Java?

JavaServer Side ProgrammingProgramming

Inheritance is a relation between two classes where one class inherits the properties of the other class. This relation can be defined using the extends keyword as −

public class A extends B{

}

The class which inherits the properties is known as sub class or, child class and the class whose properties are inherited is super class or, parent class.

In inheritance a copy of super class members is created in the sub class object. Therefore, using the sub class object you can access the members of the both classes.

Converting a sub class variable into a super class type

You can directly assign a sub class variable (value) into a super variable. In short, super class reference variable can hold the sub class object. But, using this reference you can access the members of super class only, if you try to access the sub class members a compile time error will be generated.

Example

Live Demo

class Person{
   public String name;
   public int age;
   public Person(String name, int age){
      this.name = name;
      this.age = age;
   }
   public void displayPerson() {
      System.out.println("Data of the Person class: ");
      System.out.println("Name: "+this.name);
      System.out.println("Age: "+this.age);
   }
}
public class Sample extends Person {
   public String branch;
   public int Student_id;
   public Sample(String name, int age, String branch, int Student_id){
   super(name, age);
      this.branch = branch;
      this.Student_id = Student_id;
   }
   public void displayStudent() {
      System.out.println("Data of the Student class: ");
      System.out.println("Name: "+super.name);
      System.out.println("Age: "+super.age);
      System.out.println("Branch: "+this.branch);
      System.out.println("Student ID: "+this.Student_id);
   }
   public static void main(String[] args) {        
      Person person = new Person("Krishna", 20);      
      //Converting super class variable to sub class type
      Sample sample = new Sample("Krishna", 20, "IT", 1256);      
      person = sample;
      person.displayPerson();
   }
}

Output

Data of the Person class:
Name: Krishna
Age: 20

Example

Live Demo

class Super{
   public Super(){
      System.out.println("Constructor of the Super class");
   }
   public void superMethod() {
      System.out.println("Method of the super class ");
   }
}
public class Test extends Super {
   public Test(){
      System.out.println("Constructor of the sub class");
   }
   public void subMethod() {
      System.out.println("Method of the sub class ");
   }
   public static void main(String[] args) {        
      Super obj = new Test();  
      obj.superMethod();
   }
}

Output

Constructor of the Super class
Constructor of the sub class
Method of the super class
raja
Published on 08-Feb-2021 16:04:56
Advertisements