Object Casting in Java

Previous
Next

Object casting:

  • Conversion of data from one type to another type at runtime is called casting.
  • We have discussed primitive data casting in datatypes concept.
  • Conversion of Object in Parent Child relation is called Object casting.
  • Object casting can be
    • Either upcast(Child to Parent)
    • Or Downcast(Parent to Child)

Up-casting:

  • We can store the address of Child class into Parent type variable.
  • It casts implicitly from Child to Parent.

Using parent address reference variable, we can access the functionality of Child class.

class Parent
{
	void fun(){
		System.out.println("Parent's functionality");
	}
}
class Child extends Parent
{
	void fun(){
		System.out.println("Updated in Child");
	}
}
class Upcast 
{
	public static void main(String[] args) 
	{
		Parent addr = new Child();
		addr.fun();
	}
}

Why it is calling Child functionality in the above application?

  • Hostel address = new Student();
    • address.post();  ->  reach student
  • Owner address = new Tenant();
    • address.post();  ->  reach tenant
  • Grand address = new Child();
    • address.post();  ->  reach child.
class Owner
{
	void mail()
	{
		System.out.println("Owner received the mail");
	}
}
class Tenant1 extends Owner
{
	void mail()
	{
		System.out.println("Tenant1 received the mail");
	}
}
class Tenant2 extends Owner
{
	// logic
}
class Upcast 
{
	public static void main(String[] args) 
	{
		Owner t1 = new Tenant1();
		t1.mail();

		Owner t2 = new Tenant2();
		t2.mail();
	}
}
  • Generally interface is a standard.
  • We implement interface with any identity of class.
  • After implementation, we must label the object with interface identity.
  • We always communicate with standard objects only.
interface Lenovo
{
	void processor();
	void motherBoard();
	void display();
}

class Computer implements Lenovo
{
	public void processor(){ }
	public void motherBoard(){ }
	public void display(){ }
}
class Upcast 
{
	public static void main(String[] args) 
	{
		// Computer obj = new Computer();  
		Lenovo obj = new Computer(); // recommended to give interface name.
		obj.processor();
		obj.motherBoard();
		obj.display();
	}
}

When we define an object from many implementations, we use implemented identity instead of standard identity

interface Intel
{
	void processor();
}
interface Asus
{
	void motherBoard();
}
interface LG
{
	void display();
}
class AssembledComputer implements Intel, Asus, LG
{
	public void processor(){ }
	public void motherBoard(){ }
	public void display(){ }
}
class Upcast 
{
	public static void main(String[] args) 
	{
		AssembledComputer ac = new AssembledComputer();
		ac.processor();
		ac.motherBoard();
		ac.display();

		LG l = new AssembledComputer();
		l.display();
		l.processor(); // Error : not specified by LG interface
	}
}
Previous
Next

Add Comment

Courses Enquiry Form