4

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);
    }
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
Abhishek Jain
  • 35
  • 1
  • 4
  • Check [Why is inheritance only defined at compile-time?](http://programmers.stackexchange.com/questions/224972/why-is-inheritance-only-defined-at-compile-time) – sam Oct 16 '15 at 18:03

4 Answers4

3

Inheritance is most definitely defined at compile time in 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.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

You are confused with compile time and runtime . 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 ? No right?

And the answer is

All the rules already given to Compiler from Specification. It just checks against them.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

Inheritence in java is achieved with the "extends" keyword, which is reserved for compile-time inheritence. 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());
  }
}
Nick.code
  • 1
  • 4
-1

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. and about private member although it will be inherited by the child class but wont be accessible.

Adi
  • 5
  • 1
  • 3