вторник, 13 февраля 2024 г.

Abstract class in Java

    Abstraction is a process of hiding the implementation details and showing only functionality to the user.

A class which is declared with the abstract keyword is known as an abstract class in Java

  • An abstract class must be declared with an abstract keyword.
  • It can have abstract and non-abstract methods.
  • It cannot be instantiated.
  • It can have constructors and static methods also.
  • It can have final methods which will force the subclass not to change the body of the method.

If there is an abstract method in a class, that class must be abstract.

If you are extending an abstract class that has an abstract method, you must either provide the implementation of the method or make this class abstract.

abstract class Animal {
private String name;
// Constructor
public Animal(String name) {
this.name = name;
}
// Abstract method
public abstract void makeSound();
// Concrete method
public void sleep() {
System.out.println(name + " is sleeping.");
}
// Getter method
public String getName() {
return name;
}
}

class Dog extends Animal {
// Constructor
public Dog(String name) {
super(name);
}
// Implementation of abstract method
@Override
public void makeSound() {
System.out.println(getName() + " says: Woof!");
}
}

class Cat extends Animal {
// Constructor
public Cat(String name) {
super(name);
}
// Implementation of abstract method
@Override
public void makeSound() {
System.out.println(getName() + " says: Meow!");
}
}

public class Main {
public static void main(String[] args) {
Animal dog = new Dog("Buddy");
Animal cat = new Cat("Whiskers");
dog.makeSound();
dog.sleep();
cat.makeSound();
cat.sleep();
}
}


Комментариев нет:

Отправить комментарий