Okay. So if...
int x=3;
int y=5;
x=y;
That'll make x=5, right?
Okay, so if B is a subclass of A...
A a=new A();
B b=new B();
a=b;
^^^Why is this considered upcasting?
Isn't the "a" supposed to become the "b" and not the other way around? Can someone explain all this to me?
Instead of As and Bs, let's jump to a concrete example.
class Person {
public void greet() {
System.out.println("Hello there!");
}
}
class ComputerScientist extends Person { // Does he, really?
@Override
public void greet() {
System.out.println("Hello there! I work at the Informatics Department.");
}
public void validateAlgorithm(Algorithm a)
throws InvalidAlgorithmException {
// ...
}
}
When you have a ComputerScientist as
ComputerScientist cs = new ComputerScientist();
You can access both greet and validateAlgorithm. You know (s)he is a Person, and can greet him/her as any other person. However, you may also treat him/her specifically as a ComputerScientist.
When you assign this object to a variable of type Person, all you do is saying "I don't care anymore that you are a ComputerScientist. From now on, I will treat you just as any other Person".
Person p = cs;
Which is equivalent to
Person p = (Person) cs;
The object referred by p still knows how to validateAlgorithm, and still tells you that (s)he works at the Informatics Department. However, when accessing it via p, you are telling the compiler that you only want to greet this Person, nothing else.
It is called upcasting because the variable goes up in the hierarchy tree, where up means more general/abstract and down means more specific. You're generalizing a ComputerScientist as a Person.
After a = b;, the variable a (declared with type A) will refer to an object of type B. Thus the assignment involves an implicit upcast: a = (A)b;, converting how Java views b from B to its superclass A. That's an upcast.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With