interface Readable {
public void printTitle();
}
class WebText implements Readable {
public String title;
public void printTitle(){
System.out.println("This Webpage title is "+ title);
}
public void setTitle(String title){
this.title = title;
}
}
class Blog extends WebText {
public void printTitle(){
System.out.println("The Blog title is " + title);
}
}
class ReadingTester{
public static void main(String [] arg) {
Blog b1 = new Blog();
WebText b2 = new Blog();
b1.setTitle("How to upcast");
b2.setTitle("Dangers of upcasting");
b1.printTitle();
b2.printTitle();
}
}
The above code is on a homework assignment that I am working on but I am really unsure about what is going on. When I run the code, it outputs:
The Blog title is: How to upcast
The Blog title is: Dangers of upcasting
What I am confused on is why the second one prints out "The Blog title is" instead of "This Webpage title is:". Since b2 is upcasted to a WebText shouldn't that class be the one that responds? Everything that I find online says that upcasting is safe but is this an example of when it isn't? I'm really confused and would really appreciate some help thank you so much!