java 继承编程题

本文通过三个编程实例展示了Java中的继承概念。首先定义了一个学生类,包含学号、姓名和成绩,并提供了相应的构造方法和访问器。接着创建了类A1、B1和C1,演示了构造方法的继承和调用。最后,定义了一个人类Person和其子类Student,探讨了如何在子类中继承并扩展属性和构造方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



1) 定义一个学生类,包括属性:学号(ID),姓名(name),成绩(score);构造方法(带三个参数);每个属性的访问器方法。


import java.util.Scanner;
class Student {
    String ID = " ";
    String name = " ";
    float Score = 0.0f;
    Student (String ID, String name, float Score) {
        this.ID = ID;
        this.name = name;
        this.Score = Score;
    }
    public String getID () {
        return ID;
    }
    public String getName () {
        return name;
    }
    public float getScore () {
        return Score;    
    }
}
public class Test_1 {
    public static void main (String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入学号:");
        String ID = sc.nextLine();
        System.out.println("请输入姓名:");
        String name = sc.nextLine();
        System.out.println("请输入成绩:");
        float Score = sc.nextFloat();
        Student a = new Student("3203", "张三", 100);
        System.out.println("学号:" + a.getID());
        System.out.println("姓名:" + a.getName());
        System.out.println("成绩:" + a.getScore());
    }
}



2) 创建类A1,实现构造方法中输出This is A;创建A1的子类B1,实现构造方法中输出This is B;创建B1的子类C1,实现构造方法中输出This is C


class A1 {
    A1 () {
        System.out.println("This is A!");
    }
    A1 (int i) {
    }
}
class B1 extends A1 {
    B1 () {
        super(1);
        System.out.println("This is B!");
    }
    B1 (int i) {
        super(1);
    }
}
class C1 extends B1 {
    C1 () {
        super(1);
        System.out.println("This is C!");
    }
}
public class Test_2{
    public static void main (String[] args) {
        A1 a = new A1();
        B1 b = new B1();
        C1 c = new C1();
    }
}



3) 定义一个人类(Person),它包含属性:姓名(name,性别(sex;带两个参数的构造方法;属性的访问器方法。定义上面人类的子类学生类(Student),包括属性:学号(ID),带参数的构造方法;属性的访问器方法。



class Person {
    String Name = null;
    String Sex = null;
    Person (String Name, String Sex) {
        this.Name = Name;
        this.Sex = Sex;
    }
    public String getName () {
        return Name;
    }
    public String getSex () {
        return Sex;
    }
}
class Student extends Person {
    String ID = null;
    Student (String ID) {
        super("张三", "男");
        this.ID = ID;
    }
    public String getID () {
        return ID;
    }
}
public class Test_3 {
    public static void main (String[] args) {
        Person p = new Person("李四", "男");
        Student s = new Student("511502");
        System.out.println("姓名:" + p.getName() + "\n" + "性别:" + p.getSex());
        System.out.println("姓名:" + s.getName() + "\n" + "性别:" + s.getSex() + "\n" + "学号:" + s.getID());
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值