How to access a derived class member variable by an interface object in Java?

JavaObject Oriented ProgrammingProgramming

When you try to hold the super class’s reference variable with a sub class object, using this object you can access the members of the super class only, if you try to access the members of the derived class using this reference you will get a compile time error.

Example

 Live Demo

interface Sample {
   void demoMethod1();
}
public class InterfaceExample implements Sample {
   public void display() {
      System.out.println("This ia a method of the sub class");
   }
   public void demoMethod1() {
      System.out.println("This is demo method-1");
   }
   public static void main(String args[]) {
      Sample obj = new InterfaceExample();
      obj.demoMethod1();
      obj.display();
   }
}

Output

InterfaceExample.java:14: error: cannot find symbol
      obj.display();
          ^
   symbol: method display()
   location: variable obj of type Sample
1 error

If you need to access the derived class members with the reference of super class, you need to cast the reference using the reference operator.

Example

 Live Demo

interface Sample {
   void demoMethod1();
}
public class InterfaceExample implements Sample{
   public void display() {
      System.out.println("This is a method of the sub class");
   }
   public void demoMethod1() {
      System.out.println("This is demo method-1");
   }
   public static void main(String args[]) {
      Sample obj = new InterfaceExample();
      obj.demoMethod1();
      ((InterfaceExample) obj).display();
   }
}

Output

This is demo method-1
This is a method of the sub class
raja
Published on 15-Oct-2019 06:28:24
Advertisements