Mon Aug 08, 2011 8:26 pm
interface A
{
void display();
}
class B implements A
{
public void display() {
System.out.println("Am in class B");
}
}
class C extends B
{
@Override
public void display() {
System.out.println("Am in class C");
}
}
public static void main(String[] args) {
// Upcasting from subclass to super class.
A aRef=new C();
aRef.display();//Am in class C
}
public static void main(String[] args) {
// Upcasting from subclass to super class.
A aRef=new C();
aRef.display();//Am in class C
//Downcasting of reference to subclass reference.
B bRef=(B) aRef;
bRef.display();//Am in class C
}
Am in class C
Am in class C
public class ExampleClass {
public static void main(String[] args) {
// Upcasting from subclass to super class.
A aRef=new C();
aRef.setX(43);// Compile Error
}
}
interface A
{
void display();
}
class B implements A
{
public void display() {
System.out.println("Am in class B");
}
}
class C extends B
{
private int x;
@Override
public void display() {
System.out.println("Am in class C");
}
public void setX(int x) {
this.x = x;
}
}
public class ExampleClass {
public static void main(String[] args) {
// Upcasting from subclass to super class.
A aRef=new B();
aRef.display();//Am in class C
//Downcasting of reference to subclass reference.
C bRef=(C) aRef; //ERROR
bRef.display();
}
}
interface A
{
void display();
}
class B implements A
{
public void display() {
System.out.println("Am in class B");
}
}
class C extends B
{
@Override
public void display() {
System.out.println("Am in class C");
}
}
Am in class B
Exception in thread "main" java.lang.ClassCastException: B cannot be cast to C
at ExampleClass.main(ExampleClass.java:21)
Java Result: 1
Wed Jun 12, 2013 1:54 pm
Codemiles.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com
Powered by phpBB © phpBB Group.