【问题标题】:Overriding Java code覆盖 Java 代码
【发布时间】:2014-09-29 12:00:05
【问题描述】:

我试图了解我在使用此代码时做错了什么,但我没有找到答案。为什么它不会在编译器中打印任何内容?

请帮忙。提前致谢。

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();

    }
}

【问题讨论】:

  • Why it does not print anything in the compiler? 因为编译器编译代码。您需要运行它才能看到输出。
  • @TheLostMind 不,这不是必需的。
  • 您期待什么,实际发生了什么?您的问题不清楚。
  • 因为编译器不认可您缺乏正确的格式。
  • @Kon - 正如问题所说,OP 并没有覆盖任何东西:)

标签: java


【解决方案1】:

因为你只是在编译,而不是运行代码。运行。它肯定会将结果打印到控制台。

到目前为止,您的代码中没有覆盖概念。每个孩子都是父母。您将可以访问该方法并打印 Parent (ClassA) 的实现。

来到Overriding的概念,如果你想在ClassB中看到methodA()的实现,那么你需要在ClassB中重写它,并提供与ClassB相关的实现。

【讨论】:

    【解决方案2】:

    我没有任何问题,一切正常。它打印:

    x is 0 , and y is 1
    I am an instance of:  test.ClassB
    
    Process finished with exit code 0
    

    检查您的 IDE。

    【讨论】:

    • OP说明他正在使用IDE吗?
    【解决方案3】:

    main方法的类应该是public的

    类A类{

     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() ) ;
         }
    }
    

    public 类 ClassB 扩展 ClassA { 诠释 z = 3;

    public static void main(String[] args) {
        ClassB obj1 = new ClassB();
        obj1.methodA();
    
    }
    

    }

    这行得通

    【讨论】:

    • 带有main方法的类应该是public的 不,这不是强制性的。具有 main 方法的类即使没有访问修饰符也可以运行。
    • 请检查一下并自己尝试一下:ideone.com/Qlsq6m 看看类定义。它没有声明为public class,它编译并运行良好。
    • @BackSlash,我同意你的看法。我们必须确保我们正在执行正确的类(即不要将其与文件名混淆)
    猜你喜欢
    • 2011-12-17
    • 2012-02-28
    • 1970-01-01
    • 2011-02-27
    • 2013-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-30
    相关资源
    最近更新 更多