这个想法有些含糊不清,我需要一些澄清.
我的问题是使用此代码时:
public class B {
private void don() {
System.out.println("hoho private");
}
public static void main(String[] args) {
B t = new A();
t.don();
}
}
class A extends B {
public void don() {
System.out.println("hoho public");
}
}
Run Code Online (Sandbox Code Playgroud)
输出是hoho private.
这是因为main函数与方法在同一个类中don,还是因为重写?
我已经在一本书中读到了这个想法,当我把这个main函数放在另一个类中时,我得到了一个编译器错误.
public class Parent {
public void printParent()
{
System.out.println("I am the Parent");
System.out.println("----this is ::---" + this);
this.printChild();
}
private void printChild()
{
System.out.println("This is my child");
}
}
public class Child extends Parent {
private void printChild()
{
System.out.println("I am the child");
}
}
public class RelationshipTester {
@Test
public void testRelation()
{
Child parent = new Child();
parent.printParent();
}
}
Run Code Online (Sandbox Code Playgroud)
这是输出: -
我是家长
----这是:: --- datastructures.lists.inheritance.Child@1a692dec
这是我的孩子
该对象属于Child类型,但它不调用子方法和父方法.我给了this.printChild();