java 编写三个具有继承关系的类,A、B、C(B继承A,C继承B)。 (1)设计一个类A(包含至少一个成员变量和一个方法); (2)设计一个类B继承A,继承A的非私有属性和方法,再增加至少一个成员变量和一个方法,父类已有的成员变量和成员方法不再定义; (3)设计一个类C继承B,继承B的非私有属性和方法,再增加至少一个成员变量和一个方法。 (4) 声明A、B、C类的对象,调用相关的显示信息。
时间: 2023-05-29 18:01:33 浏览: 61
A类的代码如下:
```
public class A {
protected String name;
public A(String name) {
this.name = name;
}
public void showInfo() {
System.out.println("This is class A, name is " + name);
}
}
```
B类的代码如下:
```
public class B extends A {
private int age;
public B(String name, int age) {
super(name);
this.age = age;
}
public void sayHello() {
System.out.println("Hello, I am " + name + ", " + age + " years old");
}
}
```
C类的代码如下:
```
public class C extends B {
private String gender;
public C(String name, int age, String gender) {
super(name, age);
this.gender = gender;
}
public void introduce() {
System.out.println("My name is " + name + ", " + age + " years old, " + "I am a " + gender);
}
}
```
声明对象并调用相关方法的代码如下:
```
public class Main {
public static void main(String[] args) {
A a = new A("Tom");
a.showInfo();
B b = new B("Jack", 20);
b.showInfo();
b.sayHello();
C c = new C("Lucy", 18, "female");
c.showInfo();
c.sayHello();
c.introduce();
}
}
```
输出结果如下:
```
This is class A, name is Tom
This is class A, name is Jack
Hello, I am Jack, 20 years old
This is class A, name is Lucy
Hello, I am Lucy, 18 years old
My name is Lucy, 18 years old, I am a female
```
阅读全文