1、继承
什么时候用继承关系?
- 什么是继承? 继承:实现代码重用的一种方式。
- 继承格式? extends 关键字 A类 extends B类 子类继承父类
- 继承什么? 子类继承父类的所有非私有的属性、方法
- 什么情况下用? “猫是动物,狗也是动物” 将公有属性方法放到父类,子类继承父类使用
- 继承特点? 传递性
- 类没有继承时,默认继承Object类
继承中的构造方法调用
super 关键字调用父类的 属性、 方法、构造方法
构造方法{
super(); //子类、父类构造方法加上super();语句,如果是传参数,则重写有参数的构造方法
}
方法重写
父类方法功能不能满足子类,子类重写方法里面的功能。
抽象类 abstract
在比较复杂的体系结构中,在上层作为定义而存在
什么是抽象类,抽象类有什么用,语法
多态
同一种事务在不同时刻表现不同的状态.
要有继承
要有方法重写
父类的引用 指向子类对象
final关键字
接口
1.预习继承基本语法,完成程序设计
设计一个Animal类,类中有成员变量name,age;成员方法eat();输出动物吃东西.
在动物类的基础上设计Dog,Cat类分别继承Animal.
为Dog,Cat 自己设计一个它们特有的成员变量,成员方法(自定义)
在Dog的基础上设计一个AngelDog(哮天犬) 为其也定义它特有的成员变量,成员方法(自定义)
然后写一个测试类去创建 Dog对象,AngelDog对象
//private私有化属性--外部要进行访问时—set get方法提供入口
//继承中构造方法,运行加载时,先加载父类的
package com.feifan.javaoop.Day3;
public class AnimalTest {
public static void main(String[] args) {
Dog dog = new Dog();
dog.getAge();
System.out.println("------------");
AngelDog angelDog = new AngelDog();
angelDog.DogSleep();;
angelDog.getAge();
System.out.println("------------");
Cat cat = new Cat();
}
}
package com.feifan.javaoop.Day3;
/*
动物类
private私有化属性--外部要进行访问时—set get方法提供入口
*/
public class Animal {
//成员变量
public static String generalName = "是动物";
private String name;
private int age;
public String note;
//构造方法
public Animal(){
System.out.println("动物没有Structural method");
}
//成员方法
public void eat(){
System.out.println("动物吃食物");
}
//为私有属性对外提供操作入口 访问私有属性
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
package com.feifan.javaoop.Day3;
public class Dog extends Animal{
//成员变量
String type;
//构造方法 不用写,狗继承了动物的构造方法
public Dog(){
System.out.println("狗的structural method");
}
//成员方法
public void DogSleep(){
System.out.println("狗睡觉");
}
}
package com.feifan.javaoop.Day3;
public class Cat extends Animal{
//declaration variable
String Color;
//structural method
public Cat(){
System.out.println("猫的structural method");
}
//declaration method
public void CatDrop(){
System.out.println("猫跳跃");
}
}
package com.feifan.javaoop.Day3;
public class AngelDog extends Dog {
//declaration variable
String Birthday;
//structural method
public AngelDog(){
System.out.println("哮天犬structural method");
}
//declaration method
public void AngelDogCry(){
System.out.println("哮天犬哭");
}
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-jVfhUY2R-1642658660786)(C:\Users\16431\AppData\Roaming\Typora\typora-user-images\image-20220118232402616.png)]
2.预习方法重写,在AngelDog中重写动物类中的eat(),输出 “神狗吃饭”
@Override
public void eat(){
System.out.println("神狗吃饭");
System.out.println("动物站着吃食物");
System.out.print("动物30分钟内吃完食物");
}
//override eat() 重写后调用的是子类里面重写的eat()
angelDog.eat();