【发布时间】:2013-09-17 12:55:13
【问题描述】:
我有以下代码。下面是两个问题:
class Parent {
private void test()
{
System.out.print("test executed!");
}
static void print(){
System.out.println("my class is parent");
}
}
class Child extends Parent
{
static void print(){
System.out.println("my class is Child");
}
}
public class Inheritence {
public static void main(String[] args)
{
Child p1 = new Child();
Parent p = new Child();
System.out.println("The class name of p is "+p.getClass());
System.out.println("The class name of p1 is "+p1.getClass());
System.out.println("p instance of child "+ (p instanceof Child));
System.out.println("p1 instance of child "+ (p1 instanceof Child));
//p.test();
p.print();
}
}
输出是:
The class name of p is class Child
The class name of p1 is class Child
p instance of child true
p1 instance of child true
my class is parent
我认为p 的类名将是Parent,因为它的类型是Parent。但是,它打印为Child。那么我将如何获得p 的type。
这里的第二个问题是私有方法是否被继承。虽然包括this、cmets 在内的许多文章都认为私有方法没有被继承,但我在下面的示例中看到它是被继承的。可能是下面的一些类型转换问题。
class Child1 extends Parent1
{
}
public class Parent1 {
private void test()
{
System.out.print("test executed!");
}
public static void main(String[] args)
{
Parent1 p = new Child1();
p.test();
Child1 c = new Child1();
//c.test(); The method test from parent1 is not visible
}
}
Output is : test executed!
在这里,我在 Child1 类型为 Parent1 的对象上调用 test 方法。 Child1 没有 test 方法,因为它不是继承的。但我仍然得到输出,这表明私有方法是继承的!如果test 是一个受保护的方法,并且我在子类中重写,那么尽管调用它的对象类型是parent(parent p1 = new child1());,但仍会执行被重写的方法。
编辑:经过几次 cmets,我将 Parent1 类和 Child1 类分开,并创建了一个名为 App 的新类,它构造了一个父对象和子对象。现在我不能在下面的代码中调用p.test。
class Child1 extends Parent1
{
}
class Parent1 {
private void test()
{
System.out.print("test executed!");
} }
public class App1{
public static void main(String[] args)
{
Parent1 p = new Child1();
p.test();//The method test from parent is not visible
Child1 c = new Child1();
//c.test(); //The method test from parent1 is not visible
}
}
【问题讨论】:
标签: java inheritance private classname