Let us first consider the following Java program as a simple example of Overriding or Runtime Polymorphism.
class Base { public void fun() { System.out.println( "Base fun" ); } } class Derived extends Base { public void fun() { // overrides the Base's fun() System.out.println( "Derived fun" ); } public static void main(String[] args) { Base obj = new Derived(); obj.fun(); } } |
The program prints “Derived fun”.
The Base class reference ‘obj’ refers to a derived class object (see expression “Base obj = new Derived()”). When fun() is called on obj, the call is made according to the type of referred object, not according to the reference.
The Base class reference ‘obj’ refers to a derived class object (see expression “Base obj = new Derived()”). When fun() is called on obj, the call is made according to the type of referred object, not according to the reference.
Is Overiding possible with private methods?
Predict the output of following program.
Predict the output of following program.
class Base { private void fun() { System.out.println( "Base fun" ); } } class Derived extends Base { private void fun() { System.out.println( "Derived fun" ); } public static void main(String[] args) { Base obj = new Derived(); obj.fun(); } } |
We get compiler error “fun() has private access in Base” (See this). So the compiler tries to call base class function, not derived class, means fun() is not overridden.
An inner class can access private members of its outer class. What if we extend an inner class and create fun() in the inner class?
An Inner classes can access private members of its outer class, for example in the following program, fun() of Inner accesses private data member msg which is fine by the compiler.
An Inner classes can access private members of its outer class, for example in the following program, fun() of Inner accesses private data member msg which is fine by the compiler.
/* Java program to demonstrate whether we can override private method of outer class inside its inner class */ class Outer { private String msg = "This is Kota" ; private void fun() { System.out.println( "Outer fun()" ); } class Inner extends Outer { private void fun() { System.out.println( "Accessing Private Member of Outer: " + msg); } } public static void main(String args[]) { // In order to create instance of Inner class, we need an Outer // class instance. So, first create Outer class instance and then // inner class instance. Outer o = new Outer(); Inner i = o. new Inner(); // This will call Inner's fun, the purpose of this call is to // show that private members of Outer can be accessed in Inner. i.fun(); // o.fun() calls Outer's fun (No run-time polymorphism). o = i; o.fun(); } } |
Output:
Accessing Private Member of Outer: GeeksforGeeks Outer fun()
No comments:
Post a Comment