简体   繁体   English

java中是继承编译时还是运行时

[英]Is inheritance compile time or runtime in java

I was told that inheritance is runtime, but I want to ask that if inheritance is runtime then how does compiler generate error at compile time when we try to access parent class data member via child class object:有人告诉我继承是运行时,但我想问一下,如果继承是运行时,那么当我们尝试通过子类对象访问父类数据成员时,编译器如何在编译时生成错误:

class PrivateData {
    private int x = 50;

    void show() {
        System.out.println(x);
    }
}

class ChildPrivateData extends PrivateData {

    public static void main(String s[]) {
        ChildPrivateData c1 = new ChildPrivateData();
        System.out.println(c1.x);
    }
}

Inheritance is most definitely defined at compile time in Java.继承是在 Java 编译时最明确地定义的。 I think you're confusing it with polymorphism, which, in a nutshell, states that Java chooses which overridden method to run only at runtime.我认为您将它与多态混淆了,简而言之,它指出 Java 选择仅在运行时运行的重写方法。

You are confused with compile time and runtime .您对compile timeruntime感到困惑。 I don't touch your code.我不碰你的代码。 But see an example here但在这里看一个例子

String result = returnInt();  // #1

public int returnInt() {
 return 1;
}

If you see , at line #1 do you think that compiler execute returnInt() method to give a compile time error ?如果您看到,在#1行,您是否认为编译器执行returnInt()方法会导致编译时错误? No right?没有权利?

And the answer is答案是

All the rules already given to Compiler from Specification.已经从规范中赋予编译器的所有规则。 It just checks against them.它只是检查他们。

Inheritence in java is achieved with the "extends" keyword, which is reserved for compile-time inheritence. java中的继承是通过“extends”关键字实现的,该关键字是为编译时继承保留的。 In your case you have defined the Base class variable as private.A private member is not inherited.在您的情况下,您已将基类变量定义为私有。私有成员不会被继承。 A private member can only be accessed in the child class through some Base class method.私有成员只能通过一些基类方法在子类中访问。

class PrivateData{
  private int x =50;

  void show(){
    System.out.println(x);
  }
}

class ChildPrivateData extends PrivateData {

  public static void main(String s[]){
      ChildPrivateData  c1 = new ChildPrivateData();
      System.out.println(c1.show());
  }
}

inheritance is always achieched at compile time.the code acquires reusability with extends keyword even before entering into jvm for verification and thus converting to bytecode,although we can only use its features at run-time after the creation of the object.继承总是在编译时实现。代码在进入jvm进行验证并转换为字节码之前就通过extends关键字获得了可重用性,尽管我们只能在创建对象后在运行时使用它的特性。 and about private member although it will be inherited by the child class but wont be accessible.和关于私有成员虽然它会被子类继承但不会被访问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM