我试图理解我在这段代码中做错了什么,但我找不到答案。为什么它不在编译器中打印任何东西?
请帮帮忙。提前谢谢。
public class ClassA {
int x = 0;
int y = 1;
public void methodA() {
System.out.println( "x is " + x + " , and y is " + y) ;
System.out.println( "I am an instance of: " + this.getClass().getName() ) ;
}
}
class ClassB extends ClassA {
int z = 3;
public static void main(String[] args) {
ClassB obj1 = new ClassB();
obj1.methodA();
}
}发布于 2014-08-06 21:56:54
因为您只是在编译,而不是运行代码。运行它。它肯定会将结果打印到控制台。
到目前为止,你的代码中还没有覆盖的概念。每个孩子都是父母。您将可以访问该方法,它将打印Parent (ClassA)的实现。
谈到覆盖的概念,如果您想在ClassB中看到methodA()的实现,那么您需要在ClassB中覆盖它,并提供与ClassB相关的实现。
发布于 2014-08-06 21:59:15
我没有任何问题,一切都像它应该的那样工作。它打印:
x is 0 , and y is 1
I am an instance of: test.ClassB
Process finished with exit code 0检查您的IDE。
发布于 2014-08-06 22:35:14
具有main方法的类应该是公共的
类ClassA {
int x = 0;
int y = 1;
public void methodA() {
System.out.println( "x is " + x + " , and y is " + y) ;
System.out.println( "I am an instance of: " + this.getClass().getName() ) ;
}
}公共类ClassB扩展了ClassA { int z= 3;
public static void main(String[] args) {
ClassB obj1 = new ClassB();
obj1.methodA();
}}
这是可行的
https://stackoverflow.com/questions/25162274
复制相似问题