java-类和对象练习

  1. 定义一个人的类(属性有名字,年龄,性别。写一个能输出各个属性值的方法showInfo()),定义一个学生类(属性有学号),学生继承人类,要求:
    (1)父类的属性赋值用构造方法来实现(分别用有参数构造方法和无参数构造方法实现);
    (2)子类的属性也用构造方法来赋值;
    (3)在子类中重写父类的showInfo()方法
    (4)声明学生类的对象,调用学生的显示信息的方法。
    Human类
public class Human {
	protected int sex;
	protected String name;
	protected int age; 
	
	public Human(){
		this.sex = 1;
		this.name = "xiaohong";
		this.age =15;
		
	}
	
	public Human(String name, int sex, int age) {
		this.age=age;
		this.setName(name);
		this.sex=sex;
	}

	public void printinfo(){
		System.out.print("name: "+this.getName()+" "+"sex: "+this.sex+" "+"age: "+this.age+" ");
		
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}

Student类

public class Student extends Human{
	private int id;
	
	public Student(int id,String name,int age,int sex) {
		super(name,sex,age);
//		super()
		this.id = id;
	}
	public Student(){
		super();
		this.id = 10;
	}
	public void printinfo(){
		super.printinfo();
		System.out.println("id: "+this.id);
		
	}
	

	public static void main(String[] args) {
		int id = 12;
		int age = 15;
		int sex = 0;
		String name ="w";
		
		Student s1 = new Student(id, name, age, sex);
		Student s2 = new Student();
		
		s1.printinfo();
		s2.printinfo();
		

	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值