抽象参数和方法入门
抽象类是指不能被实例化的类,其中可能包含抽象方法和抽象参数。抽象方法没有实现,需要在子类中被实现,而抽象参数则需要在子类中被具体化。
示例代码:
public abstract class Animal {
protected String name;
protected int age;
public Animal(String name, int age) {
this.name = name;
this.age = age;
}
public abstract void eat();
public abstract String sound();
public void sleep() {
System.out.println(name + " is sleeping.");
}
}
public class Dog extends Animal {
private String breed;
public Dog(String name, int age, String breed) {
super(name, age);
this.breed = breed;
}
@Override
public void eat() {
System.out.println(name + " is eating dog food.");
}
@Override
public String sound() {
return "Woof!";
}
}
public class Cat extends Animal {
private String color;
public Cat(String name, int age, String color) {
super(name, age);
this.color = color;
}
@Override
public void eat() {
System.out.println(name + " is eating cat food.");
}
@Override
public String sound() {
return "Meow!";
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog("Buddy", 3, "Golden Retriever");
Cat myCat = new Cat("Fluffy", 2, "White");
myDog.eat(); // Output: Buddy is eating dog food.
myCat.eat(); // Output: Fluffy is eating cat food.
myDog.sleep(); // Output: Buddy is sleeping.
myCat.sleep(); // Output: Fluffy is sleeping.
System.out.println(myDog.sound()); // Output: Woof!
System.out.println(myCat.sound()); // Output: Meow!
}
}