Consider the following code:
interface Pet{ String getName (); } class Bird implements Pet{ public String name; public Bird (String name){ this.name = name; } /*from w w w . j ava 2 s . co m*/ public String getName (){ return name; } } class Eagle extends Bird { public Eagle (String name){ super (name); } } public class Main { public static void main (String [] args) throws Exception { Pet f = new Eagle ("American Bald Eagle"); //PRINT NAME HERE } }
Which of the following lines of code will print the name of the Eagle object?
Select 3 options
A. System .out.println (f.name); B. System .out.println (f.getName ()); C. System .out.println (((Eagle)f).name); D. System .out.println (((Bird)f).getName ()); E. System .out.println (Eagle.name); F. System .out.println (Eagle.getName (f));
Correct Options are : B C D
While accessing a method or variable, the compiler will only allow you to access a method or variable that is visible through the class of the reference.
When you try to use f.name, the class of the reference f is Pet and Pet has no field named "name", thus, it will not compile.
But when you cast f to Bird (or Eagle), the compiler sees that the class Bird (or Eagle, because Eagle inherits from Bird) does have a field named "name" so ((Eagle)f).name or ((Bird)f).name will work fine.
f.getName()
will work because Pet does have a getName()
method.