Java 新手,仍在为 new 关键字和继承而苦苦挣扎:
public class A1 {
void a_method (){
System.out.println("Inside A1 method");
}
}
public class A2 extends A1{
void a_method(){
System.out.println("Inside A2 method");
}
}
public class TestA1A2 {
public static void main(String[] args) {
A1 a1 = new A1();
A1 a2 = new A2(); //not sure if it created object of A1 or A2
A2 a3 = new A2();
a1.a_method();
a2.a_method();
a3.a_method();
}
}
我很难理解上面代码中的 new 关键字和 if:
A1 a2 = new A2(); //not sure if it created object of A1 or A2
a2 是 A1 还是 A2 的对象?从输出中我可以看到它调用了 A2 的方法,但我真的没有得到 new 关键字。而A2是对A1的扩展,是否可以调用A1的方法??
最佳答案
A1 a2 = new A2();
此代码创建一个 A2 对象,但您只能使用 a2 访问 A1 类的方法。如果在 A2 中重写了一个方法,则调用的是 A2 的方法。
关于java - java中的新关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16635465/