As I understand the inherited class should also inherit variables, so why doesn't this code work?
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);
}
}
The Superclass reference variable can hold the subclass object, but using that variable you can access only the members of the superclass, so to access the members of both classes it is recommended to always create reference variable to the subclass.
If the members were declared protected or public , then you access them as if they were declared in your own class ( this. var , or just var if there's no ambiguity). If you have a member in the subclass with the same name as the superclass, you can use super. var to access the superclass variable.
In the definition of the inherited class, you only need to specify the methods and instance variables that are different from the parent class (the parent class, or the superclass, is what we may call the class that is inherited from. In the example we're discussing, Pet would be the superclass of Dog or Cat ).
private variables / members are not inherited. That's the only answer. Providing public accessor methods is the way encapsulation works. You make your data private and provide methods to get or set their values, so that the access can be controlled.
num
variable's access modifier is private
and private
members are not accessible out of own class so make it protected
it will accessible from subclass.
public class a {
protected int num;
...
}
Reference of Controlling Access to Members of a Class
As i understand the inherited class should inherit also variables,
you got it wrong, instance variables
are not overriden in sub-class. inheritence and polymorphism doesnt apply for instance fields. they are only visible in your sub-class if they are marked protected or public. currently you have super class variable marked private. no other class can access it. mark it either protected or public in-order for other class's to access it.
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
private
scope can only be accessed by the containing class.
For this to work num
would need to be declared protected
scope.
However this would also make it accessible to other classes in the same package. My recommedation would be to create a get
/ set
method in order to maintain proper encapsulation.
you could then access num
in class b
by calling getNum()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With