继承之猫狗案例

package 继承;
/*猫和狗分别是动物类,里面有成员变量是:姓名,年龄.颜色,
* 成员方法:set/get()
* 猫有吃的方法和睡的方法
*同样狗也有这样的方法,请用代码实现继承版本
 * 
 */
class Animal{
private String name;
private int age;
private String color;
public Animal(String name,int age,String color){
this.name=name;
this.age=age;
this.color=color;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public void eat(){
System.out.println("动物要吃饭");
}
public void sleep(){
System.out.println("动物要睡觉");
}
}
//定义猫类
class Cat extends Animal{
public Cat(String name,int age,String color){
super(name,age,color);
}


public void eat(){
System.out.println("猫要吃饭");
}
public void sleep(){
System.out.println("猫要睡觉");
}
}
//定义狗类
class Dog extends Animal{
public Dog(String name,int age,String color){
super(name,age,color);
}


public void eat(){
System.out.println("狗要吃饭");
}
public void sleep(){
System.out.println("狗要睡觉");
}
}
//测试类
public class ExtendsTest {
public static void main(String[] args) {
//创建Cat类对象
Cat c=new Cat("猫北",4,"黑色");
System.out.println("猫的名字:"+c.getName()+","+"年龄:"+c.getAge()+","+"颜色:"+c.getColor());
c.eat();
c.sleep();
System.out.println(".........");
//创建Dog类对象
Dog d=new Dog("旺旺",4,"白色");
System.out.println("狗的名字:"+d.getName()+","+"年龄:"+d.getAge()+","+"颜色:"+d.getColor());
d.eat();
d.sleep();
}
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值