Java Reference
In-Depth Information
public interface Generous {
void give();
}
public interface Munificent extends Generous {
void giveALot();
}
public class Giver {
}
public class GenerousGiver extends Giver implements Generous {
public void give() {
}
}
public class MunificentGiver extends Giver implements Munificent {
public void give() {
}
public void giveALot() {
}
}
public final class StingyGiver extends Giver {
public void giveALittle() {
}
}
Every expression in Java has two types, a compile-time type and a runtime type. The compile-time type is also
known as the static type or the declared type. The runtime type is also known as the dynamic type or the actual type.
The compile-time type of an expression is known at compile time. The runtime type of an expression is known when
the expression is actually executed. Consider the following statement:
Munificent john = new MunificentGiver();
The above code involves one variable declaration, Munificent john , and one expression, new MunificentGiver() .
The compile time type of the variable john is Munificent . The compile-time type of the expression new MunificentGiver()
is MunificentGiver . At runtime, the variable john will have a reference to an object of the MunificentGiver class and its
runtime type will be MunificentGiver . The runtime type for the expression new MunificentGiver() will be the same as its
compile-time type, which is MunificentGiver .
The instanceof operator performs compile-time check as well as runtime check. At compile-time, it checks
if it is possible for its left-hand operand to point to an instance of its right-hand operand type. It is allowed for the
left-hand operand to point to the null reference. If it is possible for the left-hand operand to have a reference of its
right-hand operand type, the code passes the compiler check. For example, the following code would compile and it
will print true at runtime:
Munificent john = new MunificentGiver();
if (john instanceof Munificent) {
System.out.println("true");
}
 
Search WWH ::




Custom Search