Java: abstract class, abstract method

An abstract class in Java is a class that declares an abstract function to be implemented in a subclass as an abstract method. An abstract method is a method that declares only what the function is, and has no real implementation part.

An abstract method is overridden in a subclass, and an abstract class can have general properties and methods as well as abstract methods.

An abstract method can be implemented with the following expression:

abstract class ClassName {
	... //General properties and methods
	abstract void AbstractMethodName(); //Abstract method declaration
	...
}
abstract class shape { //Abstract class declaration
	abstract void draw(); //Define an abstract method that has no body parts
}

class Circle extends shape {
	void draw() {
		System.out.println("Ability to draw circles");
	}
}

class Rectangle extends Shape {
	void draw() {
		System.out.println("Ability to draw rectangles");
	}
}

clas Triangle extends Shape {
	void draw() {
		System.out.println("Ability to draw triangles");
	}
}

class AbstractClass {
	public static void main(String args[]) {
		Circle c = new Circle();
		c.draw();

		Rectangle r = new Rectangle();
		r.draw();

		Triangle t = new Triangle();
		t.draw();

		System.out.println("=== Use object casting and overriding ===");

		Shape  s = new Circle(); //Assign an object of a subclass to an object of a superclass
		s.draw(); //draw() Method invocation

		s = new Rectangle();
		s.draw();

		s = new Tringle();
		s.draw();

	}
}
abstract class and abstract method example

Leave a Reply

Your email address will not be published. Required fields are marked *

Latest Post