我是一名本科大学生,试图理解Java中的继承。 docs.oracle站点表示类的所有成员都是继承的,但构造函数除外。这是有道理的。问题是我做了一个实验而且没有用。这是:
public class One{
public void outPrint(){
System.out.println("Hello World!");
}//end outPrint
}//end One.java
public class Two extends One{
//empty
}//end Two.java
public class Three extends Two{
public static void main(String[]args){
outPrint();
}//end main
}//end Three.java
当我运行Three时,我得到:非静态方法outPrint()不能从静态上下文中引用。这当然是因为编译器将outPrint()视为实例成员。如果我将关键字“static”添加到outPrint()方法标题中,整个过程就可以了。
这就是我的困惑所在。它似乎不仅仅是不可继承的构造函数,而且还有它的所有实例成员。有人能解释一下这对我好一点吗?有没有涉及使用“静态”的解决方法?我尝试了一些“超级”的实验无济于事。提前谢谢!
答案 0 :(得分:5)
您需要实例化要调用的对象。
e.g。
Three t = new Three();
t.outPrint();
您定义的main()
方法是静态的,并且没有对象的实例(One
/ Two
/ {{1} })。它仅存在于特定的命名空间中。
请注意,您可以证明Three
是-a Three
因此:
One
如果为每个子类覆盖One t = new Three();
t.outPrint();
方法,则可以根据实例化和/或引用原始对象实例的方式查看调用哪个方法。
答案 1 :(得分:1)
您正在尝试在没有实例的情况下调用非静态方法。只能使用类的isntance调用实例方法。创建一个实例,将帮助您调用该方法,如下所示:
Three threeInstance = new Three();
threeInstance.outPrint();
答案 2 :(得分:1)
为此,您需要创建class Three
或class Two
或class One
的对象。
public class Three extends Two
{
public static void main(String[]args)
{
Two t= new Two();
t.outPrint();
}
}
答案 3 :(得分:1)
试试这个
public class Three extends Two{
public static void main(String[]args){
Three three = new Three();
three.outPrint(); //outPrint() can only be called by an instance
}//end main
}//end Three.java
即使它位于同一个类中,也无法从静态方法访问非静态方法。您必须使用实例访问它们。
但是,在Three.java类中也可以使用以下内容:
public class Three extends Two{
public static void main(String[]args){
Three three = new Three();
three.printSomething("Hi");
// this will output:
// Hi
// Hello World
}//end main
public void printSomething(text) {
System.out.println(text);
outPrint(); //implicit "this" which refers to this instance....it can be rewritten as this.outPrint();
}
}//end Three.java