笔记:
1.继承 extends:
子类继承父类中所有的非私有属性和方法
构造函数不会被继承
类可以有自己的方法
2.重写(覆盖):
继承关系下,子类中的方法与父类中继承的方法名相同
参数列表相同,返回值类型相同
3.this:当前对象
this.属性;当前对象的属性
this([参数]);
super:父类对象
super.属性
super([参数]);
----------- ------------------------------------------------------------------------------------
代码案例:
1.父类
package com.zking.test;
public class Animals {
//属性
int id = 1;
String name = "加菲猫";
int age = 2;
//方法
public void eat() {
System.out.println("吃");
}
public void sleep() {
System.out.println("睡觉");
}
public void run() {
System.out.println("跑得真快");
}
//全部输出
@Override
public String toString() {
return "Animals [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
2.1 Cat 子类
package com.zking.test;
public class Cat extends Animals{
String name = "加肥猫";
public void eat() {
System.out.println("猫薄荷");
}
public void xx() {
//调用子类的name
System.out.println("猫类:"+name);
//调用父类的name
System.out.println("动物类:"+super.name);
}
@Override
public String toString() {
return "Animals [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
2.2 Dog 子类
package com.zking.test;
public class Dog extends Animals{
public void name() {
System.out.println(name);
}
//会覆盖掉父类的eat
public void eat() {
System.out.println("喜欢蘸着吃");
}
public void km() {
System.out.println("会看门");
}
@Override
public String toString() {
return "Animals [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
----------------------------------------------------------------------------------------------------------
3测试案例
package com.zking.test;
public class TestAnimals {
public static void main(String[] args) {
//创建Cat 对象
Cat c = new Cat();
c.xx();
c.eat();
System.out.println(c.toString());
System.out.println();
//创建Dog 对象
Dog d = new Dog();
d.name = "修狗"; //赋值
//调用方法
d.name();
d.eat();
d.km();
System.out.println(d.toString());
System.out.println();
}
}