Polymoprhism downcast12/24/2023 ![]() Let’s take another program where we will override super class method in sub class and will observe that can we access super class method and sub class method. Hence, in upcasting or widening, we can call all methods of super class but not sub class methods. Now, observe that we are able to call m1() method of super class.īut when we are trying to call m2() method of sub class, we got error message: compile-time error. This means that sub class object type is converted into super class type. In this example program, superclass reference is pointing to subclass object. Here, super class reference o refers to sub class object. Let’s take an example program to see the effect of upcasting where super class reference refers to sub class object. Java compiler will do the implicit casting. If we do not use the cast operator in the above case, even we will not get any error message. This kind of conversion is called upcasting or widening in java. Here, sub class object type has converted into super class type. It can be done like this: One o = (One) new Two() // Converting class Two's type into class One. We will convert object’s data type into class O using cast operator. In this statement, on the left side, the data type of reference o is One but on the right side, we got object whose data type is Two. But when a reference of class refers to different class’s object, we need casting.įor example: One o = new Two() // class One's reference o is pointing to class Two's object. Therefore, casting is not required in this case. Data type of the class object is also One. So, data type of o is One.Īt right side of assignment operator, we have class One’s object. ![]() This is because on the left side and at the right side of assignment operator (=), we have the same data type.įor example, in the first statement, o is a reference of class One. In the above two statements, we do not need casting. In this statement, class Two’s reference t is pointing to Two’s object. Similarly, sub class reference is used to point to sub class object. In the above statement, class One’s reference o is pointing or referring to One’s object.Ģ. Super class reference is used to refer to superclass object. class One is a superclass and class Two is subclass of One.ġ. Suppose class One and class Two are related classes through inheritance. Let’s understand it with the help of a suitable example. Look at the below figure, where superclass reference is pointing to the subclass object. In other words, when the subclass object type is converted into superclass type, it is called widening or upcasting.
0 Comments
Leave a Reply.AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |