JAVA自行设计一个父类和继承该父类的两个子类: (1)为每个类提供适当的成员变量和方法 (2)要求有良好的封装性,将不同类放在不同的包下面,并在类中导入其他包的类 (3)构造方法:在一个子类的构造方法中显式调用父类的构造方法,在另一个子类的构造方法中不显式调用 (4)在子类中重写父类的某(几)个方法,并在其中一个子类的重写方法中调用被重写的父类方法 (5)编写主类验证上述要求
时间: 2024-02-25 22:53:52 浏览: 138
浅谈java继承中是否创建父类对象
好的,我来为您解答。以下是JAVA的代码实现:
首先是父类Animal.java:
```java
package com.example.animal;
public class Animal {
private String name;
private int age;
private String gender;
public Animal(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getGender() {
return gender;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setGender(String gender) {
this.gender = gender;
}
public void eat() {
System.out.println("Animal is eating.");
}
public void sleep() {
System.out.println("Animal is sleeping.");
}
}
```
然后是子类Dog.java:
```java
package com.example.animal;
public class Dog extends Animal {
private String breed;
public Dog(String name, int age, String gender, String breed) {
super(name, age, gender);
this.breed = breed;
}
public String getBreed() {
return breed;
}
public void setBreed(String breed) {
this.breed = breed;
}
public void bark() {
System.out.println("Dog is barking.");
}
@Override
public void eat() {
System.out.println("Dog is eating bones.");
}
}
```
最后是子类Cat.java:
```java
package com.example.animal;
public class Cat extends Animal {
private boolean isIndoor;
public Cat(String name, int age, String gender, boolean isIndoor) {
super(name, age, gender);
this.isIndoor = isIndoor;
}
public boolean isIndoor() {
return isIndoor;
}
public void setIndoor(boolean isIndoor) {
this.isIndoor = isIndoor;
}
public void meow() {
System.out.println("Cat is meowing.");
}
@Override
public void sleep() {
System.out.println("Cat is sleeping on the sofa.");
}
}
```
最后,是主类Main.java:
```java
package com.example;
import com.example.animal.Animal;
import com.example.animal.Cat;
import com.example.animal.Dog;
public class Main {
public static void main(String[] args) {
Animal animal = new Animal("Animal", 1, "Unknown");
Dog dog = new Dog("Buddy", 3, "Male", "Golden Retriever");
Cat cat = new Cat("Lily", 2, "Female", true);
System.out.println(animal.getName() + " is a " + animal.getClass().getSimpleName());
animal.eat();
animal.sleep();
System.out.println(dog.getName() + " is a " + dog.getClass().getSimpleName() + " of breed " + dog.getBreed());
dog.eat();
dog.sleep();
dog.bark();
System.out.println(cat.getName() + " is a " + cat.getClass().getSimpleName() + " and is " + (cat.isIndoor() ? "indoor" : "outdoor"));
cat.eat();
cat.sleep();
cat.meow();
}
}
```
运行结果:
```
Animal is a Animal
Animal is eating.
Animal is sleeping.
Buddy is a Dog of breed Golden Retriever
Dog is eating bones.
Dog is sleeping.
Dog is barking.
Lily is a Cat and is indoor
Cat is eating.
Cat is sleeping on the sofa.
Cat is meowing.
```
以上就是JAVA自行设计一个父类和继承该父类的两个子类的实现和验证。
阅读全文