继承:extends
java中类只有单继承;Java多继承通过接口实现;
如果定义一个类时,没有extends,则父类为java.lang.Object
方法的重写:overwrite
在子类中需要对父类中的方法重写时,必须具有相同的方法名,参数列表和返回类型。
super:
通过super访问父类中的方法和属性;
普通函数:没有顺序限制
构造函数:若是第一行没有显式调用super(),那么java会默认调用super
继承和组合
is-a:关系使用继承;爬行动物也是动物
has-a:关系使用组合;动物有姓名,年龄,吃饭等属性;
package mypro01; public class Animal { String name; int age=20; public void eat() { System.out.println("the animal is eating"); } public Animal() { //所有的构造函数第一句是super(),如果不手动添加,编译器会自动添加 super(); System.out.println("create an animal"); } } class Mammals extends Animal{ String habbit; //重写方法override public void eat() { //调用父类的属性age System.out.println(super.age); //调用父类的eat方法 super.eat(); System.out.println("the mammals is eating"); } public void sleep(){ System.out.println("the mammals is sleeping"); } } class Reptiles extends Animal{ String life; public void play() { //调用父类的eat方法 super.eat(); System.out.println("the reptiles is playing"); } }
原文:https://www.cnblogs.com/hapyygril/p/12353113.html