java 继承编程题

来源:互联网 发布:json unicode转中文 编辑:程序博客网 时间:2024/05/29 12:30



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());
    }
}


0 0
原创粉丝点击