111 01 Android 零基础入门 02 Java面向对象 04 Java继承(上)02 继承的实现 01 继承的实现

111 01 Android 零基础入门 02 Java面向对象 04 Java继承(上)02 继承的实现 01 继承的实现

本文知识点: 继承的实现

说明:因为时间紧张,本人写博客过程中只是对知识点的关键步骤进行了截图记录,没有对截图步骤进行详细的文字说明(后面博主时间充裕了,会对目前的博客编辑修改,补充上详细的文字说明);有些步骤和相关知识点缺乏文字描述,可能会难以理解。读者如有不明之处,欢迎博客私信或者微信(本人微信在博客下方的“关于博主”处)与本人交流,共同进步

继承的实现

继承实现需要的关键字-extends

mark
mark

注意:Java中的继承只能是单继承,即子类只能有一个父类。
mark

好比一个孩子来自一个亲爹。
mark

继承代码实现

父类-Animal类

public class Animal {	
	private String name ;// 昵称
	protected int month;// 月份
	String species ;// 品种
	
	public Animal() {
	
	}

	public String getName() {
		return name;
	}

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

	public int getMonth() {
		return month;
	}

	public void setMonth(int month) {
		this.month = month;
	}

	public String getSpecies() {
		return species;
	}

	public void setSpecies(String species) {
		this.species = species;
	}

	// 吃东西
	public void eat() {
		System.out.println(this.getName() + "在吃东西");
	}
}

子类1-Cat类

public class Cat extends Animal{
	private double weight;//体重
	public Cat(){
		
	}
	
	public double getWeight() {
		return weight;
	}

	public void setWeight(double weight) {
		this.weight = weight;
	}
	
	//跑动的方法
	public void run(){
		System.out.println(this.getName()+"是一只"+this.getSpecies()+",它在快乐的奔跑");
	}
}

子类2-Dog类

public class Dog extends Animal {
	private String sex;//性别
	
	public Dog(){
		
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}
	
	//睡觉的方法
	 public void sleep(){
		 super.eat();//调用的哪个eat();
		 super.species="犬科";
		 System.out.println(this.getName()+"现在"+this.getMonth()+"个月大,它在睡觉~~");
	 }
}

测试类-Test

import com.imooc.animal.Animal;
import com.imooc.animal.Cat;
import com.imooc.animal.Dog;

public class Test {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Cat one=new Cat();
		one.setName("花花");
		one.setSpecies("中华田园猫");
		one.eat();
		one.run();
		System.out.println("===================");
		Dog two=new Dog();
		two.setName("妞妞");
		two.setMonth(1);
		two.eat();
		two.sleep();
	}
}

测试效果:
mark

注意:子类可以访问父类的非私有成员,父类的私有成员,子类是无法获取到的。
子类独有的成员,其他的兄弟类无法访问到的。
父类也不能访问子类自己特有的属性和方法。
mark

mark

posted @ 2020-10-09 16:17  皿哥的技术人生  阅读(175)  评论(0编辑  收藏  举报