OPC原则(开闭原则)
open close prrinciple
对底层开放,对修改关闭。可扩展性
关键字super
super 指代父类
super()指代父类无参构造方法。只能出现在构造方法中第一行,只能出现一次。
super不代表父类无参构造的地址
super 和 this 一样,不能出现在static修饰的方法中。
private 修饰的不能被显示继承
父类的一切都可以被子类继承
基础数据类型,方法名相同,返回值不同时重写不成功(编译不通过)
引用数据类型,父类中返回值类型一定要比子类中返回值类型高
向上转型Dog --> Animal 向下转型Animal --> Dog(不通过)
class Animal{
public Animal(){
System.out.println("父类无参构造执行!");
}
}
class Dog extends Animal{
public Dog(){
System.out.println("子类的无参构造执行!");
}
}
class Test{
public static void main(String[] args){
new Dog();
}
}
运行结果:
class Test{
public static void main(String[] args){
Dog dog = new dog();
Cat c = new cat();
SiYang sy = new SiYang;
sy.feed(dog,"骨头");
sy.feed(c,"鱼");
}
}
class Animal{
public void eat(String[] args){
}
}
class Dog extends Animal{
public void main(String food){
System.out.println("小狗吃"+food);
}
}
class Cat extends Animal{
public void eat(String food){
System.out.println("小猫吃"+food);
}
}
class SiYang{
public void feed(Dog d,String foodName){
d.eat(foodName);
}
public void food(Cat c,String foodName){
c.eat(foodName);
}
}