Monday, May 13, 2013

Tutorial 16: Abstract Classes in java




Code:

AbstractClass.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package AbstractDemo;

/**
 *
 * @author Ankit
 */
public abstract class AbstractClass {
    int x;
    int y;
   
    public void getData(){
        System.out.println("im in getData of Ab Class...");
    }
   
    public abstract void getData(int a, int b);
}


AbstractSubClass.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package AbstractDemo;

/**
 *
 * @author Ankit
 */
public class AbstractSubClass extends AbstractClass{

    @Override
    public void getData(int a, int b) {
        System.out.println("I am in getData of subclass...");
    }
   
}

AbstractClassMain.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package AbstractDemo;

/**
 *
 * @author Ankit
 */
public class AbstractClassMain {
    public static void main(String[] args) {
        AbstractClass ob1 = new AbstractClass() {

            @Override
            public void getData(int a, int b) {
                    System.out.println("im in getDAta with arguments of Main class....");
            }
        };
       
        ob1.x = 10;
        ob1.y = 20;
        ob1.getData();
        ob1.getData(ob1.x, ob1.y);
       
        AbstractSubClass ob2 = new AbstractSubClass();
        ob2.getData(10, 20);
    }
}


Note:

If a class extends an abstract class, it has to implement (override) all the abstract methods of that abstract class.

No comments:

Post a Comment