Abstract classes & Methods in Java

Specifying a class with keyword abstract indicates that it can’t be instantiated. You can create the instance of the class by using new operator. Suppose you want to write a super class wherein certain methods are implemented and some methods are abstract methods (just method signatures without any implementation ). Point to be noted about abstract classes and methods are as follow:

  • To define an abstract class keyword abstract must be used
  • An abstract class can’t be instaniated
  • An abstract method can’t be contained in a non-abstract class
  • If an abstract classes is extended in a non-abstract sub class, all the abstract methods must be implemented
  • A class that contains abstract methods must be defined abstract
  • An abstract class can’t be instaniated using the new operator but still constructors can be defined which are invoked by its sub classes
  • It is possible to define a class abstract with no abstract methods
  • A subclass can be abstract even if its superclass is concrete
  • A sub class can override a method from its super class to define it abstract
  • You can’t create the instance of an abstract class but it can be used as data type

Example 1

package abstract_classes;

abstract class Light {
    // Data fields in abstract class
    int     noOfWatts;       // wattage data
    boolean indicator;       // on or off
    String  location;        // placement location

    // Instance methods / non abstract methods with implementation
    public void switchOn()  { indicator = true; }
    public void switchOff() { indicator = false; }
    public boolean isOn()   { return indicator; }

    // Abstract Instance Method without implementation
    abstract public double kwhPrice();               // (1) No method body
}
class TubeLight extends Light {
    // Data field in sub class
    int tubeLength;

    // Implementation of inherited abstract method.
    public double kwhPrice() { return 2.05; }        // (2) Method body is written in subclass
}

public class Factory {
    public static void main(String[] args) {
        TubeLight cellarLight = new TubeLight();     // (3) OK
        Light nightLight;                            // (4) OK
    //  Light tableLight = new Light();              // (5) Compile time error. We can't instantiate 
        nightLight = cellarLight;                    // (6) OK
        System.out.println("KWH price: " + nightLight.kwhPrice());
    }
}

Example 2

public class LivingDemo {

	public static void main(String[] args) {
		LivingThing obj = new Human();
		
		System.out.println(obj.walk());
		
		obj = new Dog();
		System.out.println(obj.walk());
	}

}

abstract class LivingThing {
	abstract String walk();
}

class Human extends LivingThing {
	public String walk(){
		return "Human walks on two legs";
	}
}

class Dog extends LivingThing {
	public String walk(){
		return "Dog walks on four legs";
	}
}

No Responses