I am going through the inheritance topic exercises. I am not sure why I am
getting ClassCast Exception where as it supposed to work. The following
code is as per Exercise 4.2 except that I did not remove the code related
to Method overriding and Implicit Casting.
Note: If I just have only the two lines of code as follows in main method,
it works fine.
Person person1 = new Person();
Student student3 = (Student) person1;
Not sure where is the conflict coming from that is leading to ClassCast
Exception.
package mypeopleexample;
public class Main {
public static void main(String[] args) {
System.out.println("---- Observe method overriding behavior...");
Person person1 = new Person();
person1.myMethod("test1");
Student student1 = new Student();
student1.myMethod("test2");
InternationalStudent intStudent1 = new InternationalStudent();
intStudent1.myMethod("test3");
// Polymorphic behavior and Implicit casting
System.out.println("---- Observe Runtime polymorphic behavior
----");
// Implicit casting - Student object instance is type of Person.
//Object instance is looked at the runtime not just type
//on which the method is called
Person person2 = new Student();
person2.myMethod("test4");
Person person3 = new InternationalStudent();
person3.myMethod("test5");
Student student2 = new InternationalStudent();
// This is an implicit type casting between InternationalStudent
and Student class.
student2 = intStudent1;
student2.myMethod("test6");
System.out.println("---- Explicit casting ----");
//Explicit Type Casting to make a person student type
* //Getting ClassCastException on this one. Reason ?*
Student student3 = (Student) person1;
}
}
*
*
--
You received this message because you are subscribed to the Google Groups
"JPassion.com: Java Programming" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
Visit this group at http://groups.google.com/group/jpassion_java?hl=en-US.
For more options, visit https://groups.google.com/groups/opt_out.