多态

一.面向对象的特性:继承 封装 多态
1.封装-保证数据安全-属性私有化
2.多态—需要继承做基础,多种形态,重载
调用方法时,先找父类,没有会报错,有则会继续去子类中找,若有则执行子类方法,若无则执行父类方法
3.设计模式 -单例模式(懒汉式,饿汉式)
一个类最多只允许创建一个对象
(构造函数私有)
4.== 和equals的区别
==:用于判断基本数据类型
Equals用于判断引用数据类型
5.包装类
byte - Byte
short - Short
int - Integer
long - Long
float - Float
double - Double
char - Character
boolean- Boolean
6.instanceof:关键字 判断对象是否是该类实例
例1. 1.定义一个Animal父类,方法有eat();
2.定义三个子类;
Cat,Dog,Eagle;
每个子类增加新的方法,并重写eat();
3.利用多态性
定义一个Animal类型的变量a,并将不同子类的实例赋给a;
调用eat();观察结果后,并理解多态
4.思考,如果a的引用指向一个Cat,如何调用Cat的新增方法;

   public class Animal {
        private Animal a;
    	public void eat() {		
    	}
    }
    public class Cat extends Animal{
    	 public  void eat(){
    		 System.out.println("吃早饭");
    	 }
    	public class Dog extends Animal {
        	 public  void eat(){
        		 System.out.println("吃午饭");
        	 }
    }
     public class Eagle extends Animal {
    	 public  void eat(){
    		 System.out.println("吃晚饭");
    	 }
    }

例2. 定义一个Animal类,方法有sing方法,定义这个类的三个子类(Dog,Cat,Bird),分别重写这个方法。利用多态,定义一个Animal类型的对象,Animal a;分别引用三个子类的对象,调用sing方法。为每个子类,增加额外的方法。

    public class Animal2 {
    private Animal a;
    public void sing(){	
  } 
    public void eat(){
		
	}
	public void play(){
		
	}
}
  public class Dog2 extends Animal2{
    	public void sing(){
    		System.out.println("汪汪汪");
    	}
    	public void eat(){
    		System.out.println("吃骨头");
    	}
    	public void play(){
    		System.out.println("遛弯");
    	}
}
    public class Cat2 extends Animal2 {
	public void sing(){
		System.out.println("喵喵喵");
	}
}
  public class Bird2 extends Animal2{
    public void sing(){
    		System.out.println("吱吱吱");
    	}
}
public class Test2 {
	public static void main(String[] args) {
		Animal2 d= new  Dog2();
		d.sing();
		d.eat();
		d.play();
		Animal2 c = new Cat2();
		c.sing();
		Animal2 b = new Bird2();
		b.sing();

	}

}

例3. 模拟天天酷跑游戏;
定义一个(宠物)Pet类,类中有属性name,方法是follow(跟随);再定义三个子类,Cat,Dog,Eagle,分别重写follow方法;
再定义一个Hero类,这个类中有两个属性name和Pet类型的pet,一个方法run(),再定义两个构造方法,Hero(String name,);Hero(String name,Pet pet);
run()方法的代码是Hero跑,并且他的宠物也跟着跑;
编写测试类来操作Hero

 public class Hero {
    private String name;
    private Pet pet;
    public  void run(){	
     System.out.println(this.name+"跑 ");
     pet.follow();
    }
	public Hero(String name) {
		super();
		this.name = name;
	}
	public Hero(String name, Pet pet) {
		super();
		this.name = name;
		this.pet = pet;
	}
   
}
 public class Pet {
    public String name;
    public  void follow(){
    	
    }
}
public class Cat extends Pet{
    	 public  void follow(){
    	    	
    	    }
}

    public class Dog extends Pet {
    	 public  void follow(){
    	    	
    	    }
}
public class Test3 {
	public static void main(String[] args) {
		Hero h = new  Hero("后裔");
		h.run();
	}

}

你可能感兴趣的:(多态)