apparent and real classes

apparent and real classes - 1 apparent and real classes The...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
1. apparent and real classes The apparent class (or apparent type) of an expression is a syntactic property; it is used to determine what component references are syntactically legal. For a class variable, its apparent class is the class with which it was declared. The real class (or real type) of an expression is a semantic property. It is the class of the value of the expression, and it can change while the program is executing. The real class of an expression determines which components are actually referenced—for a call to a public method, the overriding method in the real class is called. Java widens the instance of a class to an instance of one of its superclasses. Widening an object takes no time (at runtime) but just changes the syntactic view of the object. Java syntax: class cast ( class-name ) class-expression Example: ( Executive ) d Meaning: evaluation yields a view of the value of class-expression with apparent type class-name . It does not change the real type. Caution: casting an expression can only be done to its real type or any super class of its real type. Casting an object of a subclass to its superclass type is a widening cast, and visa versa. Commands d.method() is legal only if variable method method() is available in the apparent class of d. However, the method referenced depends on the real class of d, and not on the apparent class of d. (example below E3) Examples: Consider Three classes, animal, dog and cat. public class Animal{ public String classtype= "animal"; public String toString() { return "animal"; } public String getType() { return "classtype is " +classtype; } public int number() { return 1; } } public class Dog extends Animal{ public String classtype= "Dog"; public String classtype2= "type2"; public String getSound() { return "woof woof"; } public String getType() { return "classtype is " +classtype; } } public class Cat extends Animal{ public String classtype= "Cat"; public String toString() { return "Cat”; } public String getSound() { return "meow"; } public int getAge() { return 2; } }
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
E1. If
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 02/08/2010 for the course CS 00 taught by Professor Staff during the Fall '08 term at Cornell.

Page1 / 5

apparent and real classes - 1 apparent and real classes The...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online