Abstract Class and Abstract Method in Java
In Java, an abstract class is a class that cannot be instantiated directly, and is typically used as a superclass to provide a common interface and behavior to its subclasses. An abstract method is a method that does not have an implementation, and must be implemented by a concrete subclass.
Here are some key characteristics of abstract classes and methods in Java:
- Abstract Class:
- An abstract class is declared using the
abstract
keyword. - An abstract class can have both abstract and non-abstract methods.
- An abstract class may also have fields, constructors, and non-abstract methods.
- An abstract class cannot be instantiated directly, but can be used as a reference type for its subclasses.
Here's an example of an abstract class:
javapublic abstract class Animal {
protected int legs;
public Animal(int legs) {
this.legs = legs;
}
public int getLegs() {
return legs;
}
public abstract void makeSound();
}
In this example, the Animal
class is declared as abstract, and has a protected field for the number of legs. It also has a constructor and a non-abstract method for getting the number of legs, as well as an abstract method for making a sound.
- Abstract Method:
- An abstract method is declared using the
abstract
keyword, and ends with a semicolon instead of a method body. - An abstract method must be implemented by any concrete subclass that extends the abstract class that declares the abstract method.
Here's an example of a concrete subclass that extends the Animal
class:
javapublic class Dog extends Animal {
public Dog() {
super(4);
}
public void makeSound() {
System.out.println("Woof!");
}
}
In this example, the Dog
class extends the Animal
class, and implements the makeSound
method.
In general, abstract classes and methods are used to provide a common interface and behavior for a group of related classes, while allowing for variation in the implementation of that behavior by the concrete subclasses. They can be used to create abstractions and decouple different parts of a program.
Comments
Post a Comment