Showing posts with label Method Overriding in Java. Show all posts
Showing posts with label Method Overriding in Java. Show all posts

Saturday, August 11, 2012

Method Overriding in Java

public class First {

public void abc ()
{
System.out.println("First");
}

public void xyz ()
{
System.out.println("First_XYZ");
}
}

------------------------------------------------------------------------------------------

public class Second extends First {
public void abc ()
{
System.out.println("Second");
}

public static void main(String args[])
{
First first = new First();
first.abc();//First

Second sec = new Second();
sec.abc();//Second

First cc = new Second();
cc.abc();//Second

Object a = new Second();
System.out.println(a.getClass());//class Second

First fs = (First) new Second();
fs.abc();//Second



/************************************/
First c = new Second();
c.xyz();//First_XYZ as there is no xyz() method in this class

First f = (First) new Second();
f.xyz();//First_XYZ as there is no xyz() method in this class

/************************************/
Second dd = (Second) new First();
dd.abc();//java.lang.ClassCastException: First cannot be cast to Second

}
}



------------------------------------------------------------------------------------------
First
Second
Second
class Second
Second
First_XYZ
First_XYZ
java.lang.ClassCastException: First cannot be cast to Second
at Second.main(Second.java:34)