0

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?

user10335564
  • 133
  • 3
  • 16
  • `((B) a).getLandlord()` will throw a ClassCastException if `a` is an instance of `A` – Brandon G Dec 12 '18 at 18:01
  • @BrandonG I think I understand that, but I have one more question: I'm a little confused because the parent class takes one parameter when the constructor is called, but the child class takes two parameters when the constructor is called. Would this be why a ClassCastException is generated? Is this an inappropriate downcast? – user10335564 Dec 12 '18 at 18:38
  • The number of parameters to the constructors doesn't really matter. The ClassCastException happens because you pass in `new A("Johnson")`, which is an instance of `A` and cannot be cast to `B`. To avoid the exception, you would have to pass in something like `new B("Johnson", "Smith")`, which can then be safely cast to `B` because it is an instance of `B` – Brandon G Dec 12 '18 at 20:36

0 Answers0