I have 2 classes, A and B which B inherits from A. Both classes have a property of type int called w.
In class A w is public and in class B w is private.
I made an object of type A using B constructor - A a = new B()
Yet when i tried to access B's properties i found out i can only access variables or methods from class A even though i made an object of type B.
I thought that this was only relevant if both classes didnt have the same methods or variables. But in this case both classes have a variable named w yet i can only access the value stored in the A class. Why is this so?
class A
public class A {
public int w;
private static String str = "K";
public A() {
str+="B";
w+=str.length();
str+=w;
}
@Override
public String toString() {
return str.charAt(w-2)+"P";
}
}
class B
public class B extends A {
public static int w = 2;
private String str = "W";
public B(int x) {
w+=super.w;
str+=super.toString()+w;
}
@Override
public String toString() {
return super.toString() + str;
}
}
Testing class
public class Q1 {
public static void main(String[] args) {
A a = new A();
A a2 = new B(1);
System.out.println(a);
System.out.println(a.w);
System.out.println(a2);
System.out.println(a2.w);
B b = new B(2);
System.out.println(b);
}
}