一、动态绑定
指在执行期间(run,分配内存)而非编译期间判断所引用对象的实际类型,根据实际类型调用相关方法。
其存在的必要条件
要有继承
要有重写
父类引用指向子类对象
package practice;
class Animal{
private String name;
Animal(String name){
this.name=name;
}
public void enjoy(){
System.out.println("叫声........");
}
}
class Cat extends Animal{
private String eyescolor;
Cat(String name,String color){
super(name);
this.eyescolor=color;
}
public void enjoy(){
System.out.println("猫叫.........");
}
}
class Dog extends Animal{
private String furcolor;
Dog(String name,String color){
super(name);
this.furcolor=color;
}
public void enjoy(){
System.out.println("狗叫。。。。。。");
}
}
class Lady{
private String name;
Animal pet;
Lady(String name,Animal animal){
this.name=name;
this.pet=animal;
}
public void myPetEnjoy(){
pet.enjoy();//根据new的对象来决定调用哪一个方法
}
}
public class TestLady {
public static void main(String args[]){
Cat cat=new Cat("mimi","black");
Dog dog=new Dog("wangwang","white");
Lady l1=new Lady("lili",cat);
Lady l2=new Lady("wenwne",dog);
l1.myPetEnjoy();
l2.myPetEnjoy();
}
}
结果:猫叫.........
狗叫。。。。。。
共有三个enjoy()函数,所以myPetEnjoy()函数中具体调用哪一个enjoy()函数由new的对象来决定
二、抽象类及抽象方法
抽象方法类似c++中的纯虚函数
含有抽象方法的类必须声明为抽象类
抽象类不能被实例化,也可以理解为没有构造函数,抽象方法必须被重写
package practice;
abstract class Animal{
abstract void getinfo();
}
class Pig extends Animal{
private String name;
private int height;
private int weight;
Pig(String name, int height, int weight) {
this.name=name;
this.height=height;
this.weight=weight;
}
void getinfo(){
System.out.println("name:"+name+" "+"height:"+height+" "+"weight:"+weight);
}
}
public class _abstract {
public static void main(String args[]){
Pig pig=new Pig("lulu",20,30);
pig.getinfo();
}
}
结果:name:lulu height:20 weight:30
三、接口
classextendsimplements
一种特殊的抽象类
只包含public static final常量和抽象方法,但是abstract可以省略
接口特性:
多重实现(一个类可以实现多继承)
接口中只能定义抽象方法,而且这些方法只能默认为public
接口可以继承其他接口 package practice;
interface Singer{
public int age=20;
public void sing();
public void sleep();
}
interface Painter{
public int age=30;
public void paint();
public void sleep1();
}
class People implements Singer,Painter{
@Override
public void sing() {
// TODO Auto-generated method stub
System.out.println("I'm singing......");
}
@Override
public void sleep() {
// TODO Auto-generated method stub
System.out.println("I'm sleep......");
}
@Override
public void paint() {
// TODO Auto-generated method stub
System.out.println("I'm sleeping....");
}
@Override
public void sleep1() {
// TODO Auto-generated method stub
System.out.println("You are sleeping...");
}
}
public class TestInterface {
public static void main(String args[]){
People people=new People();
people.sing();
people.sleep();
people.paint();
people.sleep1();
}
结果:I'm singing......
I'm sleep......
I'm sleeping....
You are sleeping...