Java继承 细节

继承可以解决代码复用,当多个类有相同的属性和方法时,可以定义一个父类,在父类中定义相同的属性和方法,子类在定义自己特有的属性和方法的同时可以直接继承(extends)父类中所有的属性及方法

细节:

public class Testtest{
	public static void main(String[] args){
		Cat cat = new Cat("刮刮乐", 3, 10.8);
		System.out.println(cat.Test());
		Dog dog = new Dog("奶酪",20,12);//
		System.out.println(dog.Test());
	}
}

//父类
class Animal{
	private int age;
	public double high;
//父类无参构造器
	public Animal(){
		System.out.println("父类无参构造器被调用");
	}
//父类有参构造器
	public Animal(int age, double high){
		setAge(age);
		this.high = high;
	}

//封装
	public void setAge(int age){
		if(age <= 15 && age >= 1){
			this.age = age;
		}else{
			System.out.println("age不在范围内,已设定为2岁");
			this.age = 2;
		}
	}
	public int getAge(){
		return age;
	}
}
//子类
class Cat extends Animal{
	private String name;
	public Cat(String name, int age, double high){
		super(age, high);//用super调用指定的父类有参构造器
		this.name = name;
	}
	public String Test(){
		return "name =" + this.name + " 今年" + getAge() + "岁了" + "有" + high + "高";
	}//非私有的high可以直接访问,私有的age借助主类的公共方法访问
}
//子类
class Dog extends Animal{
	private String name;
	public Dog(String name, int age, double high){//什么都不写默认调用父类无参构造
		this.name = name;
		setAge(age);
		this.high = high;
	}
	public String Test(){
		return "name =" + this.name + " 今年" + getAge() + "岁了" + "有" + high + "高";
	}//非私有的high可以直接访问,私有的age借助主类的公共方法访问
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值