Heading

Thursday, September 19, 2013

Abstract Class Example in Java

 

Example:
abstract class MyClass
{
 public  abstract void display();
}

class FirstClass extends MyClass
{
 public void display()
 {
  System.out.println("method of first class");
 }
 public void firstMethod()
 {
  System.out.println("method of first class first method");
 }
 public void firstMethod1()
 {
  System.out.println("method of first class first method1");
 }
}

public class AbstractCheck extends FirstClass
{
 public void display()
 {
  System.out.println("method of AbstractCheck class");
 }
 public void firstMethod()
 {
  System.out.println("method of AbstractCheck class first method");
 }
 public void secondMethod()
 {
  System.out.println("method of AbstractCheck  class second method");
 }
 public static void main(String... s)
 {
  AbstractCheck mc=new AbstractCheck();
  mc.display();
  mc.firstMethod();
  mc.firstMethod1();
  mc.secondMethod();


 }
}

Output:
G:\company\java programs>javac AbstractCheck.java

G:\company\java programs>java AbstractCheck
method of AbstractCheck class
method of AbstractCheck class first method
method of first class first method1
method of AbstractCheck  class second method


Note:-  The methods which are available in reference class are only allowed you to access with the reference.

public static void main(String... s)
 {
  FirstClass mc=new AbstractCheck();
  mc.display();
  mc.firstMethod();
  mc.firstMethod1();
  mc.secondMethod();
 }

will cause you compile time error because scondMethod() does not exist in FirstClass

G:\company\java programs>javac AbstractCheck.java
AbstractCheck.java:42: error: cannot find symbol
  mc.secondMethod();
    ^
  symbol:   method secondMethod()
  location: variable mc of type FirstClass
1 error

No comments:

Post a Comment