Does inheritance in java inherit variables?

As I understand it, the inherited class must inherit variables as well, so why is this code not working?

public class a {
    private int num;

    public static void main(String[] args) {
        b d = new b();
    }
}

class b extends a {
    public b() {
        num = 5;
        System.out.println(num);
    }
}

      

+3


source to share


6 answers


num

variable modifier private

and private

members are not available from native class, so make it protected

accessible from subclass.

public class a {
     protected int num;
     ...
}

      



Reference Control access to class members

+10


source


public class A{
    public int num=5;
    public static void main(String[] args) {
        b d = new b();
        d.c();
    }
}

class b extends A
{
    public void c() 
    {
        System.out.println(num);
    }
}

      



definitely this is what you need i think

+2


source


private

the scope can only be accessed using the class.

For this to work, num

you must declare an area protected

.

However, this will also make it available to other classes in the same package. My recommendation would be to create a get

/ method set

to maintain proper encapsulation.

you can access num

in the class b

by callinggetNum()

+1


source


As I understand it, an inherited class must inherit and variables,

you are wrong, instance variables

do not override in subclass. inheritance and polymorphism do not apply to instance fields. they are only visible in your subclass if they are marked as protected or public. you currently have a superclass variable marked as private. no other class can access it. mark it as either protected or public for another class to access it.

+1


source


Since you are using the private access modifier . If you use private for an instance variable or for a method , it can only access the inside of the class (even multiple classes include one source file), We can expose the private variable to the outside using getters and setters. The following code will compile without errors

public class A {
    private int num;

public void setNum(int num)
{
     this.num = num;
}

public int getNum() 
{
      return num;
    }


    public static void main(String[] args) 
{
        B d = new B();
    }


  }
  class B extends A
       {

      public B()
 {

        SetNum(5);
        System.out.println(getNum());
     }
   }

      

+1


source


You don't have access to the private members of the base classes from the subclass. Only members with private / protected modifiers

0


source







All Articles