How and when can we cast from one class to another?

How and when can we cast from one class to another?

An instance of one class can be casted to another, with one restriction : The source and destination classes must have inheritance relation – one class must be a sub class of the other class. Explicit class casting is a must, when using super class objects where sub class objects are expected. Access to the methods and variables that are defined in the subclass is gained. To cast an object to another class, the syntax is
(classname) object

where class name is the name of the destination class, and object is a reference to the source object. Casting always creates a reference to the old object of the type classname; the old object continues to exist.

Casing one object to another is needed in the situation where Java2D graphics operations are used. A Graphics class object must be casted to a Graphics2D object before drawing on screen. The following example illustrate this. to create a new Graphics2D object called screen2D:
Graphics2D screen2D = (Graphics2D)screen;

Graphics2D is a subclass of Graphics, and both are in the java.awt package.

How and when can we cast from one class to another?

Java allows us to cast variables of one type to another as long as the casting happens between compatible data types.

Example:
class A
{
     void hello()
     {
          System.out.println(“Hello”);
     }
}

class B extends A
{
     void hi()
     {
          System.out.println(“Hi”);
     }
}

A a = new A();
A b = new B(); // Upcasting OK
B c = new A(); // gives error
How to send to receive datagram packet?
To send or receive a packet, the sockets send or receive methods can be used: socket.send(packet); socket.receive(packet);....
Difference between field variable and local variable
Field variables: Variable that are declared as a member of a class. OR Variables declared outside any method/constructor but inside the class block......
When do we need to flush an output stream?
If any bytes that are previously written and have been buffered by the implementation of the output stream...
Post your comment