栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java、方法重写

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java、方法重写

方法重写规则:

  1. 方法名相同
  2. 参数列表相同
  3. 返回值类型相同或者是其子类
  4. 访问权限不能严于父类

 方法重写注意

  1. 子类根据需求对从父类继承的方法进行重新编写
  2. 重写时,可以用super.方法的方式来保留父类的方法
  3. 构造方法不能被重写
案列: 

第一部分、创建一个动物类

public class Animal {
	private String name;
	private int health;
	private int love;

	public Animal() {
		super();//调用父类Object类里的无参构造方法
	}

	public Animal(String name, int health, int love) {
		super();//调用父类Object类里的无参构造方法
		this.name = name;
		this.health = health;
		this.love = love;
	}

	public String getName() {
		return name;
	}

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

	public int getHealth() {
		return health;
	}

	public void setHealth(int health) {
		this.health = health;
	}

	public int getLove() {
		return love;
	}

	public void setLove(int love) {
		this.love = love;
	}

	// 定义一个输出动物信息的方法
	public void print() {
		System.out.println("动物昵称:" + this.name + ",健康值:" + this.health
				+ ",亲密度:" + this.love);
	}

}

第二部分:创建一个动物类的子类----小狗类

public class Dog extends Animal {
	private String strain;

	public Dog() {
		super();// 调用Animal类里的无参构造方法
	}

	public Dog(String name, int health, int 	love, String strain) {
		super(name, health, love);// 调用Animal类里的有参构造方法
		this.strain = strain;
	}

	public String getStrain() {
		return strain;
	}

	public void setStrain(String strain) {
		this.strain = strain;
	}
	
	public void print(){
		super.print();
		System.out.println("宠物品种:"+this.strain);
	}

}

第三部分:创建一个动物类的另一个子类----猫类

public class Cat extends Animal {
	private String color;

	public Cat() {
		super();
	}

	public Cat(String name, int health, int love, String color) {
		super(name, health, love);
		this.color = color;
	}

	public String getColor() {
		return color;
	}

	public void setColor(String color) {
		this.color = color;
	}
	
	//重新定义父类里的print()方法
	public void print(){
		//输出宠物的所有信息
		super.print();
		System.out.println("宠物颜色:"+this.color);
	}
}

第四部分:创建一个测试

public class Test {

	public static void main(String[] args) {
		Cat cat1 = new Cat("敦敦", 88, 99, "黄色");
		cat1.print();
		
		Dog dog1 = new Dog("来福", 99, 90, "泰迪");
		dog1.print();
	}

}

代码测试结果

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/992383.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号