JAVA. Can inner classes be used to exhibit polymorphism. Explain with a coded example.
Expert Answer
Yes, Inner class be used to exhibit polymorphism. Inner class holds implicit reference to its containing object. Inner class can access private methods of its containing class.
Example:
class Parent {
public static void main(String[] args) {
new Parent().InnerClass().yourfunc();
new Child().InnerClass().yourfunc();
}
public A InnerClass() {
return InnerClass();
}
private final class InnerClass implements A {
public void yourfunc() {
System.out.println(“parent inner class”);
baz();
}
}
public void baz() {
System.out.println(“from parent”);
}
}
class Child extends Parent {
public void baz() {
System.out.println(“from child”);
}
}
interface A {
void yourfunc();
}