-1

I have the following code:

public class A {
 private Integer a=7;
 
 public int get_a() {
    return a;
    
 }

}
public class B extends A{

}

public class Main {

    public static void main(String[] args) {

        B obiect1=new B();
       System.out.println( obiect1.get_a());
    
       
    }

}

The Variabile "a" is private so will not be inherited by class B, but method "get_a()" is public so it will be inherited by class B. In "main()" method when I call "obiect1.get_a()" what will happen sice class B doesn't have variabile "a"? It will show 7 on console but why? B doesn't inherited variabile "a". What is actually happen

jdaz
  • 5,964
  • 2
  • 22
  • 34
Ica Sandu
  • 105
  • 5
  • 3
    The private variable _is_ inherited. `B` does have the `a` variable. It's just not directly accessible because it was declared private. – khelwood Jul 13 '20 at 21:06
  • So simple, thank you! – Ica Sandu Jul 13 '20 at 21:10
  • Does this answer your question? [What is the difference between public, protected, package-private and private in Java?](https://stackoverflow.com/questions/215497/what-is-the-difference-between-public-protected-package-private-and-private-in) – Woodchuck Jul 13 '20 at 21:27

1 Answers1

0

With the use of the extends keyword, the subclass B will be able to inherit all the properties of the superclass A except for the private properties of the superclass, but with the help of a public getter, get_a() in this case, it is possible to access variable a from Class A.

CyberDev
  • 1
  • 3