I have two question on this code
public class Override {
private void f() {
System.out.println("private f()");
}
public static void main(String[] args) {
Override po = new Derived();
po.f();
}
}
class Derived extends Override {
public void f() {
System.out.println("public f()");
}
}
/*
* Output: private f()
*/// :~
1) How is function f is visible on the reference of Override po;
2) Why is output "private f()"
You are accessing Override's own method even if the object is derived because as per scope rules, the private members of class are considered first, and as its written in scope of Override it is referencing the private f, and since its private its not overriden in Derived class at all, they will only override if method signature is same.
Thsi is the correct code which will call Derived's f
The override of method has three conditions.child class must has the same name and parameters and returned value as its super class.But if both of the parameter and returned value are vary,so the override is not exist!even if the two method are different method!ok!like this:
Eclipse will not talk error! because the method addV in class Child is different with the method addV in class Parent.As your instance!
The
main
method is inside classOverride
, so ofcourse it can see the private members of classOverride
.You are not overriding method
f
in classDerived
, there is no polymorphism. The type of the variablepo
isOverride
, so it will take methodf
from classOverride
.Note that method
f
in classOverride
is not visible at all in classDerived
. The methodf
in classDerived
is a different method, that doesn't have anything to do with the methodf
in the superclass.