Sunday, July 4, 2010

Java Abstract Class Examples


1. How to create an abstract Class and its sub classes
2. How to create a static method in abstract Class

1. How to create an abstract Class and its sub classes

package basics;

public abstract class AbstractClassExample {

public static void main(String[] args) {
Lion lion = new Lion("Mr Lion", 4);
lion.printName();
System.out.println(lion.canWalkWithTwoLegs());

Bear bear = new Bear("Mr Bear", 4);
bear.printName();
System.out.println(bear.canWalkWithTwoLegs());
}
}

abstract class Animal {
private String name = null;
private int numberOfLegs = 0;

public Animal(String name, int numberOfLegs) {
super();
this.name = name;
this.numberOfLegs = numberOfLegs;
}

public abstract boolean canWalkWithTwoLegs();

public void printName() {
System.out.println("Name is: " + name);
}
}

class Lion extends Animal {

public Lion(String name, int numberOfLegs) {
super(name, numberOfLegs);
}

public boolean canWalkWithTwoLegs() {
return false;
}
}

class Bear extends Animal {

public Bear(String name, int numberOfLegs) {
super(name, numberOfLegs);
}

public boolean canWalkWithTwoLegs() {
return true;
}
}

There will be a zip file created at
Name is: Mr Lion
false
Name is: Mr Bear
true


2. How to create a static method in abstract Class

package basics;

public abstract class AbstractClassExample {

public static void main(String[] args) {
AbstractClassExample.doSomeThing();
}

public static void doSomeThing() {
System.out.println("What can i do?");
}
}


There will be a zip file created at
What can i do?

No comments:

Post a Comment