I am trying to trace some code and the relationship between a parent and child class. The parent class has the following definition:
public class A implements Comparable<A> {
private String owner;
public A(String s) {
owner = s;
}
//More methods related to this class
}
Suppose B
is derived (a child class) from A
and B
has a String type instance variable called landlord
, which also has a getter method (called getLandlord()
). B
also has two String parameters in the constructor: owner
and landlord
. Would the declaration and constructor of B
look like this?
public class B extends A {
private String landlord;
public B(String s, String landlord) {
super(s); //From parent class
this.landlord = landlord;
}
}
I also have a method that should return the landlord
whenever the actual parameter is an instance of B
. The original code I wrote was this:
public static String house(A a) {
return a.getLandlord();
}
This returned a compiler error, and I used casting to try to avoid this compiler error:
public static String house(A a) {
return ((B) a).getLandlord();
}
When I write this code:
B.house(new A("Johnson"))
will I get the String landlord
because I am using downcasting?