Upcasting

Baran Aslankan
BAU Yazılım ve Bilişim Kulübü
2 min readDec 2, 2021

Hey guys, today i prepared a writing about upcasting, first start with what is upcasting and why do we need it then we’ll see some examples.

What is Upcasting ?

Typecasting the child reference or object to the parent reference or object.

Why Upcasting ?

More flexible, accessing the parent class members and methods.

Example

class School{
public void msg() {
System.out.println("School Class");
}

}
public class Student extends School {
@Override
public void msg() {
System.out.println("Student Class");
}
}
class Test{

public static void main(String[] args) {
School s=new School();
School st=new Student();
say(s);
say(st);


}
public static void say(School s) {
s.msg();
}

}

In this example School is the parent class and Student is the child class, i created two objects one is normal School object and the other one is upcasted Student object, Student class has a method override from School class. I also created a static method and gave that method School object as a parameter, when i call that method in my main method i will have the output down bellow.

This is the part where upcasting is very nice and useful, i called the same method with different parameters and i got the outputs depending their class. Since Student is a child class of School i can write upcasted Student object as a parameter and the method that is going to be executed is in the Student class.

This becomes very useful where you have a lot of override methods and subclasses, you cant just upcast the objects and call them in the same method for getting the results you wanted.

class School{
public void msg() {
System.out.println("School Class");
}

}
public class Student extends School {
@Override
public void msg() {
System.out.println("Student Class");
}
public void msg2() {
System.out.println("Print me");
}
}
class Test{

public static void main(String[] args) {
School s=new School();
School st=new Student();
//say(s);
//say(st);
st.msg2();


}
public static void say(School s) {
s.msg();
}

}

Here i added msg2 method in Student class and i tried to call that method with my ucpasted object.

Note that the “st” object is upcasted and thus we can’t use subclass method and we will have that error.

That was all from me today, thanks for reading and see you on the next writing ;)

--

--