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);
}
}
Since the type of variable
ais [class]A, the variable can only access members and methods of classA(depending on the access specifiers) – even though the actual type of variableais classB.Refer to method paintComponent, in class
javax.swing.JComponent. The type of the method parameter isGraphicsbut the actual type of the parameter is Graphics2D (which extendsGraphics). However, in order to access the methods ofGraphics2D, you must first cast the parameter, i.e.This is a fundamental aspect of the object-oriented paradigm.
Refer also to the comment to your question by @ArunSudhakaran
Similarly, if you want variable
ato access thewmember of classB, you need to casta.If you are using at least Java 14, you can use Pattern Matching for the instanceof Operator
Also refer to the book Effective Java by Josh Bloch.