Does inheritance in java inherit variables?
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
source to share
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()
source to share
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.
source to share
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());
}
}
source to share