what is absttract class in java
- User
what is absttract class in java
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
what is absttract class in java
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
In Java, an abstract class is a class that cannot be instantiated on its own and is designed to be inherited by other classes. It provides a way to define a blueprint for other classes to follow and can contain both abstract and non-abstract methods.
abstract keyword.public abstract class Animal {
private String name;
public Animal(String name) {
this.name = name;
}
public String getName() {
return name;
}
public abstract void makeSound();
public void eat() {
System.out.println(name + " is eating.");
}
}
public class Dog extends Animal {
public Dog(String name) {
super(name);
}
@Override
public void makeSound() {
System.out.println("Woof!");
}
}
public class Cat extends Animal {
public Cat(String name) {
super(name);
}
@Override
public void makeSound() {
System.out.println("Meow!");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog("Buddy");
Cat cat = new Cat("Whiskers");
System.out.println(dog.getName());
dog.makeSound();
dog.eat();
System.out.println(cat.getName());
cat.makeSound();
cat.eat();
}
}
default keyword (Java 8 and later).In summary, abstract classes in Java provide a way to define a blueprint for other classes to follow, share code, and provide a common base class for related classes. They are particularly useful when you want to define an interface and provide a partial implementation that can be shared by its subclasses.