- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to access a derived class member variable by an interface object in Java?
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
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
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
- Related Articles
- How to initialize const member variable in a C++ class?
- How to access the fields of an interface in Java?
- How to access Static variable of Outer class from Static Inner class in java?
- How to access an object value using variable key in JavaScript?
- How to write a class inside an interface in Java?
- How to write/declare an interface inside a class in Java?
- How to instantiate member inner class in Java?
- What is the default access for a class member in C#?
- How to implement an interface using an anonymous inner class in Java?
- How to declare a class and an interface in JShell in Java 9?
- What happens when more restrictive access is given to a derived class method in C++
- How to access the object of a class without using the class name from a static context in java?
- How to declare member function in C# interface?
- How to create an object from class in Java?
- Can we define an interface inside a Java class?

Advertisements