Tuesday, 29 October 2013

Class Types in java how to make class and object and class and object mechanism in java


The name of a class can be used to specify the type of a reference. If a variable is declared as a class type, the variable either containsnull or a reference to an object of that class or a subclass of that class. It is not allowed to contain any other kinds of values. For example:
class Shape { ... }
class Triangle extends Shape { ... }
...
Shape s;
Triangle t;
...
s = t;
This example declares a class called Shape and a subclass of Shape called Triangle. The code later declares a reference variable called s that can contain a reference to a Shape object and another variable called t that can contain a reference to a Triangle object. The value of s can be assigned to the value of t because an object is not only an instance of its declared class, but also an instance of every superclass of its declared class. Since instances of the Triangle class are also instances of its superclass Shape, the Java compiler has no problem with s = t.
However, saying t = s generates an error message from the compiler. Java does not allow a reference variable declared as a class type to contain a reference to a superclass of the declared class. The assignment t = s is illegal because Shape is a superclass ofTriangle. The assignment can be accomplished if s is first cast to a reference to Triangle:
t = (Triangle)s;
The cast operation ensures that the object referenced by s is a class type that is either Triangle or a descendant of Triangle. When you cast an object reference to a subclass of the reference type, you are saying that you want to treat the object being referenced as an instance of the specified subclass. If the compiler cannot determine whether the argument of a cast will be of the required type, the compiler generates runtime code that ensures that the argument really is an instance of the specified subclass. At runtime, if the class of the object being referenced is not an instance of the specified subclass, a ClassCastException is thrown. 

No comments:

Post a Comment