Introducing Java Upcasting And Downcasting Concepts

 

Upcasting And Downcasting


Upcasting

Upcasting is a type of object typecasting in which a child object is typecasted to a parent class object. By using the Upcasting, we can easily access the variables and methods of the parent class to the child class. Here, we don't access all the variables and the method. We access only some specified variables and methods of the child class. Upcasting is also known as Generalization and Widening.


In Casting, it is not possible to access big data from small data. But it is possible to access small data from big data.


Putting something in the Super Class (Object, Variable, Method) in the Sub Class (Object, Variable, Method) is called "Upcasting".


class A {

}

class B extends A {

}

class Test {

A a = new A();

B b = new B();

b = a;

a = b;

}


In Upcasting, what is simply done is to give a Sub Class Object to the Super Class Variable.


Downcasting


Turning the Sub Class Object cast into a Super Class Variable back into a Sub Class Variable is called "Down Casting".


class A {
}
class B extends A {
}

A a = new A();
B b = new B();
A a = new B();
B b = new A();
Downcasting

Giving the Super Class Variable to the Sub Class Variable.
(Only if Sub Class Object is used as a Parameter.)


GitHub Projects


Comments

Popular posts from this blog

Introducing Java Encapsulation Concept

Introducing Java Interfaces Concept

Introducing Java Method Overriding And Super Keyword