i have this example:
class One
{
public void testOne(){System.out.println("One!!!");}
public void testTwo(){System.out.println("One!!!");}
}
public class Jenia extends One
{
static void test(One o) {o.testOne(); o.testTwo();}
public static void main(String args[])
{
test(new One());
}
}
Results:
One!!!
One!!!
ok, no questions.
than, i try modified my code:
only this method:
public static void main(String args[])
{
t开发者_开发知识库est(new Jenia());
}
results:
One!!!
One!!!
ok, we have this results because - here upcasting(Jenia-One).
its all ok too, but, modified again:
in class Jenia override method
testOne`:
public void testOne(){System.out.println("Two!!!");}
so i have this code:
class One
{
public void testOne(){System.out.println("One!!!");}
public void testTwo(){System.out.println("One!!!");}
}
public class Jenia extends One
{
public void testOne(){System.out.println("Two!!!");}
static void test(One o){o.testOne(); o.testTwo();}
public static void main(String args[])
{
test(new Jenia());
}
}
and results:
Two!!!
One!!!
my question: why Two!!! ?? why we not lost override methods?
Because all the methods in Java are virtual in terms of C++/C# and all the values passed by reference. So when you call some method, the type of the reference is irrelevant, what is important is the type of the object it points to. In your case the object is of Jenia type, so Jenia method gets called.
Thats the desired behaviour.. which method gets called depends on the runtime type, not the reference type. Since the obect is type of Jenia
, the Jenia
version of testOne
gets called, even if the reference is type of One
. Thats plain old polymorphism.
See the explanation in comments
class One
{
public void testOne(){System.out.println("One!!!");}//method one
public void testTwo(){System.out.println("One!!!");}//method two
}
public class Jenia extends One
{
public void testOne(){System.out.println("Two!!!");}//method 3
static void test(One o){o.testOne(); o.testTwo();}//method 4
public static void main(String args[])
{
test(new Jenia());//calls method 4 which in turns calls 3 and 2.
}
}
}
When you call o.testOne()
in test
method, it calls Jenia.testOne
since the o
is an instance of Jenia
. You can check it by o.getClass().getName();
.
java overriding here is the tutorial http://download.oracle.com/javase/tutorial/java/IandI/override.html
public class A {
void print() {
System.out.println("A");
}
public static void main(String[] args){
A a1 = new A();
a1.print(); // A
A a2 = new B();
a2.print(); // B ! because it overrides print method
B b = new B();
b.print(); // B
}
}
class B extends A {
void print() {
System.out.println("B");
}
}
精彩评论