继承、封装练习

需求:
1.鱼类:
属性:年龄、 重量
方法:自我介绍 、游泳
-2鸟类
属性:年龄 、颜色
方法:自我介绍 、飞
分析
使用继承:
-
抽取出动物类:属性(年龄)、方法(自我介绍)
鱼类继承动物类、提供特有属性: 重量和特有方法 :游泳。
鸟类继承动物类、提供特有属性:颜色和特有方法:飞
开发测试类,进行测试
–使用封装
属性私有 方法public 提供对应的构造方法
-
效果图
分析:通过阅读上面要求。我们可以获得几个信息:
1.创建一个Animal 的父类,其属性有 年龄(age),方法:自我介绍 (introduce)
2.Fish类中有自己的属性:重量(weight)、方法(swim)
3.Bird类中有自己的属性:颜色(color)、方法(fly)
编写代码:
/*父类Animal/
public class Animal {

private int age;

//创建set get方法
public void setAge(int age){
this.age = age;
}
public int getAge(){
return age;
}
//创建构造方法
public Animal(){
}
public Animal(int age){
this.age = age;
}
//创建父类独有的方法
public String introduce(){
return “我是父类介绍的方法”;
}
}


/*创建Fish类/

/**创建Fish类*/
public class Fish extends Animal{
private double  weight;
//创建set get 方法
public void setWeight(double weight){
this.weight = weight;
}
public double getWeight(){
return  weight;
}
//创建构造方法
public  Fish(){
}
public Fish(int age,double weight){
super(age);//age 是父类私有属性,用super调用
this.weight = weight;
}
//子类重写父类的方法:
public String introduce(){
return "我是一条"+weight+"斤重的鱼!"+"\n我今年"+super.getAge()+"岁了\n"+this.swim();
}
//创建子类独有的方法
public String  swim(){
return "我在水里悠闲的吐泡";
/**由于上面introduce是连接的字符创 this.swim所以这个方法要换成带有返回值类型的*/
}
}

/*创建Bird类/
/*创建Bird类/
public class Bird extends Animal{
private String color;
//创建set get 方法
public void setColor(String color){
this.color = color;
}
public String getColor(){
return color;
}
//创建构造方法
public Bird(){
}
public Bird(int age,String color){
super(age);//age 是父类私有属性,用super调用
this.color = color;
}
//子类重写父类的方法:
public String introduce(){
return “我是一只”+color+”的鸟!”+”\n我今年”+super.getAge()+”岁了\n”+this.fly();
}
//创建子类独有的方法
public String fly(){
return “我展翅翱翔”;
/*由于上面introduce是连接的字符创 this.swim所以这个方法要换成带有返回值类型的/
}
}


/*创建测试类Test/
/*创建测试类Test/
public class Test{
public static void main(String[] args) {

Fish f = new Fish(2,5);
System.out.println(f.introduce());
Bird b = new Bird(5,”红色”);
System.out.println(b.introduce());
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值