what is abstract method in java
A defined method without an implementation is referred to as an abstract method in Java. Instead, it is up to the subclasses that derive from the abstract class to implement the method. When a base class wants to offer a method signature that all of its subclasses must implement but the base class itself is unable to do so, an abstract method is often employed.
The "abstract" keyword in the method declaration is used to declare an abstract method in Java. Here's an example
what is abstract method in java
Abstract methods in java mean those methods that stand declared with the usage of abstract keywords inside an abstract class. These do not have any definition per se and thus, are called abstract methods in Java.
public abstract class Animal {
public abstract void makeSound();
}
abstract method Example in Java Programming:
abstract class Animal {
String Name = " ";
Animal(String name) {
this.Name = name;
}
// we can declare non-abstract methods in abstract class.
public void Information(String detail) {
System.out.println("The details of " + this.Name + " is: " + detail);
}
// declaring the signatures of abstract methods
abstract public void legs();
abstract public void eyes();
}
class Camel extends Animal {
// constructor
Camel(String name) {
super(name);
}
// Overriding or defining the abstract methods:
@Override
public void legs() {
System.out.println("It has 4 legs.");
}
@Override
public void eyes() {
System.out.println("It has 2 eyes.");
}
}
class Pigeon extends Animal {
// constructor
Pigeon(String name) {
super(name);
}
// Overriding or defining the abstract methods:
@Override
public void legs() {
System.out.println("It has 2 legs.");
}
@Override
public void eyes() {
System.out.println("It has 2 eyes.");
}
}
class Ant extends Animal {
// constructor
Ant(String name) {
super(name);
}
// Overriding or defining the abstract methods:
@Override
public void legs() {
System.out.println("It has 6 legs.");
}
@Override
public void eyes() {
System.out.println("It has 2 eyes.");
}
}
public class Test {
public static void main(String[] args) {
// creating the object of child classes and using Animal class reference.
Animal object1 = new Camel("Camel");
object1.Information("Camels are found in desert.");
object1.legs();
object1.eyes();
System.out.println();
Animal object2 = new Pigeon("Pigeon");
object2.Information("Pigeons are intelligent animals.");
object2.legs();
object2.eyes();
System.out.println();
Animal object3 = new Ant("Ant");
object3.Information("there are over 12,000 ant species worldwide.");
object3.legs();
object3.eyes();
}
}
No comments:
Post a Comment