继承
java使用 extends 和 implements 这两个关键字来实现继承.
- extends 一个子类只能拥有一个父类,只能继承一个类。
- implements 可以同时继承多个接口,多个接口逗号隔开。
public class Animal {
private String name;
public Animal(String myName) {
name = myName;
}
Animal() {
System.out.println("animal no name");
}
public void eat(){
System.out.println("animal eat");
}
}
public class Dog extends Animal {
Dog() {
//这里是省略了super()
System.out.println("dog no name");
}
public Dog(String myName) {
super(myName);
super.eat(); //super指向的是父级
this.eat(); //this 调用自己的方法
}
@Override
public void eat(){
System.out.println("dog eat");
}
}
public class Main {
public static void main(String[] args) {
Dog dog1 = new Dog("jack");
Dog dog2 = new Dog();
}
}
重写
当一个子类继承一个父类时,可以对其父类的方法重写,其参数列表与被重写方法的参数列表必须完全相同。如上面代码中Animal的eat方法在dog中重写。
重载
在一个类里面,同一个方法名,传的参数不同,而执行不同。其参数是必须修改的,返回值类型可以修改。
public int test(){
System.out.println("1");
return 1;
}
public void test(int a){
System.out.println("2");
}