basic2_inherit

public class Animal{
String type;
int age;
int id;
double height;
double weight;
String area;

void eat(){
System.out.println(this.type+" Animal eat!");
}

//无参构造函数 都写一下   方便将来被继承
public Animal() {
// int num = 10;
//若写了 super 必须放第一行
// super() 代指父类的构造方法
super();// 调用父类(object)的构造函数
this.type = "Animal";
this.id = 1;
}








public Animal(String area) {
//若构造函数 第一句话没写 super();
// 相当于自动执行 父类无参的构造函数
this.type = "Animal";
this.area = area;
}


@Override
public String toString() {
return "Animal [type=" + type + ", age=" + age + ", id=" + id + ", height=" + height + ", weight=" + weight
+ ", area=" + area + "]";
}



}


CAT



/*----
 * 面向对象三大特性: 继承   封装   多态
 * 继承:
 * 在原有类型基础上  拓展生成新的类型 
 * 子类有父类的所有 成员(属性/方法)
 * 
 * class 子类名  extends 父类名
 * 所有类  都是 Object  的子类
 * 
 * 
 * ---*/


public class Cat extends Animal{

//子类可以有  和父类相同的属性
//  若是子类引用 则访问 子类属性
//     父类属性依然存在   但必须用父类引用访问
//  利用这样的特性 实现子类对父特性的一些修改
String type;
String id;

public Cat(String type,String id){
//子类可以继承父类的构造方法
//  只能直接使用在这里  不能 直接  new Cat(xxx,xxx)
this.type = type;
this.id = id;
}

void catchMouse(){
//super.属性  代指当前实例的 父类部分
System.out.println(this.id+"猫抓老鼠"+super.id);
}


@Override
public String toString() {
return "Cat [type=" + type + ", id=" + id + "]"+super.toString();
}



}

MAIN

public class MainTest {


public static void main(String[] args) {
Cat xiaohei = new Cat("Cat", "are1");// 

System.out.println( xiaohei.type);
xiaohei.catchMouse();

//将一个对象转换成字符串  方便打印观察
System.out.println(xiaohei);
System.out.println(xiaohei.toString()); 
}


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值