zoukankan      html  css  js  c++  java
  • java基础---多态(一)

    1.什么是多态?

    同一个引用类型,使用不同的实例而执行不同操作(父类引用,子类对象)

    2.如何实现多态

    1-使用多态实现思路

    2-编写父类

    3-编写子类,子类重写父类方法

    运行时,使用父类的类型,子类的对象

    向上转型 Pet pet = new Dog(); 自动类型转换

    注意:实现多态的两个要素:子类重写父类方法、使用父类的类型

    3.实现多态的两种形式

    使用父类作为方法形参实现多态

    使用父类作为方法返回值实现多态

    4.使用父类作为方法形参实现多态

    举例:

    public class Master{

    /*

     * 1.首先在父类提取子类的共同的方法  抽取方法

     * 2.使用多态实现

     *  

     */  

    public void feed(Pet pet){

      pet.eat();

    }

    }

     

     

    package text;

    public abstract class Pet {

     

    /*宠物类*/

    private String name;

    private int love;

    private int health;

     

    //默认访问权限

    int num;

     

    /*

     * get.set

     *

     * */

    public String getName() {

    return name;

    }

    public void setName(String name) {

    this.name = name;

    }

    public int getLove() {

    return love;

    }

    public void setLove(int love) {

    this.love = love;

    }

    public int getHealth() {

    return health;

    }

    public void setHealth(int health) {

    this.health = health;

    }

     

     

     /*

      *

      * 带参数的方法

      *

      * */

    public Pet(String name, int love, int health) {

    super();

    this.name = name;

    this.love = love;

    this.health = health;

    }

     

     

    /*

     *

     *

     * 不带参数的方法

     *

     * */

    public Pet() {

    super();

    // TODO Auto-generated constructor stub

    }

     

    //重写

    @Override

    public String toString() {

    return "Pet [name=" + name + ", love=" + love + ", health=" + health

    + ", num=" + num + "]";

    }

    //抽象方法

    public abstract void print();

     

        //多态

    public abstract void eat();

     

    }

     

     

    package text;

    public class Dog extends Pet{

     

    private String strain;

    /*

     * get.set

     *

     * */

    public String getStrain() {

    return strain;

    }

     

    public void setStrain(String strain) {

    this.strain = strain;

    }

    /*

      *

      * 带参数的方法

      *

      * */

    public Dog(String name, int love, int health, String strain) {

    super(name, love, health);

    this.strain = strain;

    }

    /*

      *

      * 不带参数的方法

      *

      * */

    public Dog() {

    super();

    System.out.println(super.num);  //默认访问权限

    // TODO Auto-generated constructor stub

    }

    //重写

    public void print() {

    System.out.println("name="+super.getName()+"love="+super.getLove()+"health="+super.getHealth()+"strain="+strain);

    }

     

    //多态

    @Override

    public void eat(){

    System.out.println("dog eat...");

    super.setHealth(getHealth()+3);

    }

    }

     

     

     

    package text;

    public class Test {

    public static void main(String[] args) {

     

     

    //多态

        

        Dog d=new Dog("00",100, 60, "金毛");

        Master m=new Master();

        m.feed(d);

        System.out.println("dog="+d.getHealth());   

    }

     

     

    }

     

    6. 使用父类作为方法返回值实现多态

     

    举例:

     

    package text2;

    public class Master{

    public Pet getPet(String typeId){

     Pet p=null;

    if (typeId.equals("dog")) {

      p=new Dog("dd",10,10,"金毛");

    }else if(typeId.equals("penguin")){

      p=new Penguin();

    }

        return p;

      }

    }

     

     

    package text2;

    public class Dog extends Pet{

    private String strain;

     

     

    /*

     * get.set

     *

     * */

    public String getStrain() {

    return strain;

    }

     

    public void setStrain(String strain) {

    this.strain = strain;

    }

    /*

      *

      * 带参数的方法

      *

      * */

    public Dog(String name, int love, int health, String strain) {

    super(name, love, health);

    this.strain = strain;

    }

     

     

    /*

      *

      * 不带参数的方法

      *

      * */

    public Dog() {

    super();

    System.out.println(super.num);  //默认访问权限

    // TODO Auto-generated constructor stub

    }

       

    //重写

    public void print() {

    System.out.println("name="+super.getName()+"love="+super.getLove()+"health="+super.getHealth()+"strain="+strain);

    }

     

       @Override

       public void eat() {

    // TODO Auto-generated method stub

    System.out.println("dog eat...");

       }

    }

     

     

    package text2;

    public abstract class Pet {

    /*宠物类*/

    private String name;

    private int love;

    private int health;

     

    //默认访问权限

    int num;

     

    /*

     * get.set

     *

     * */

    public String getName() {

    return name;

    }

    public void setName(String name) {

    this.name = name;

    }

    public int getLove() {

    return love;

    }

    public void setLove(int love) {

    this.love = love;

    }

    public int getHealth() {

    return health;

    }

    public void setHealth(int health) {

    this.health = health;

    }

     

     

     /*

      *

      * 带参数的方法

      *

      * */

    public Pet(String name, int love, int health) {

    super();

    this.name = name;

    this.love = love;

    this.health = health;

    System.out.println("父类有参的构造方法");

    }

     

     

    /*

     *

     *

     * 不带参数的方法

     *

     * */

    public Pet() {

    super();

    System.out.println("父类无参的构造方法");

    // TODO Auto-generated constructor stub

    }

     

     

    //重写

    @Override

    public String toString() {

    return "Pet [name=" + name + ", love=" + love + ", health=" + health

    + ", num=" + num + "]";

    }

    //抽象方法

    public abstract void print();

     

        //多态

    public abstract void eat();

     

    }

     

     

     

    package text2;

    public class Penguin extends Pet{

    private String gender;

    /*

     * get.set

     *

     * */

    public String getGender() {

    return gender;

    }

     

    public void setGender(String gender) {

    this.gender = gender;

    }

     

    /*

      *

      * 带参数的方法

      *

      * */

    public Penguin(String name, int love, int health, String gender) {

    super(name, love, health);

    this.gender = gender;

    }

     

    /*

      *

      * 不带参数的方法

      *

      * */

    public Penguin() {

    super();

    // TODO Auto-generated constructor stub

    }

    //重写

    @Override

    public void print() {

    System.out.println("name="+super.getName()+"love="+super.getLove()+"health="+super.getHealth()+"strain="+gender);

     

    }

     

    @Override

    public void eat(){

    System.out.println("penguin eat...");

     

    }

     

    }

     

     

     

     

     

     

     

    package text2;

    public class Test {

    public static void main(String[] args) {

     

        

          /*

       * 多态的第二重实现

       * 父类作为返回值

       *  

       */

          Master m=new Master();

          Pet p=m.getPet("dog");

          p.eat();

         }

    }

     

    7.多态的高级转低级(父类到子类的转换)

     

    package test3;

    public class Master{

     

    public void feed(Pet pet){

    /*

     * 主人和宠物玩耍

     * 多态的高级转低级

     * a instanceof b

     * */

     

    public void play(Pet pet){

    if (pet instanceof Dog) {

    Dog d=(Dog) pet;

    d.catchingFlyingDisks();

    }else if(pet instanceof Penguin){

    Penguin p=(Penguin) pet;

    p.swimming();

     

    }

    }

     

    }

     

    package test3;

    public class Dog extends Pet{

    private String strain;

    /*

     * get.set

     *

     * */

    public String getStrain() {

    return strain;

    }

     

    public void setStrain(String strain) {

    this.strain = strain;

    }

    /*

      *

      * 带参数的方法

      *

      * */

    public Dog(String name, int love, int health, String strain) {

    super(name, love, health);

    this.strain = strain;

    }

     

     

    /*

      *

      * 不带参数的方法

      *

      * */

    public Dog() {

    super();

    System.out.println(super.num);  //默认访问权限

    // TODO Auto-generated constructor stub

    }

    //重写

    @Override

    public void print() { System.out.println("name="+super.getName()+"love="+super.getLove()+"health="+super.getHealth()+"strain="+strain);

    }

     

    //多态

    @Override

    public void eat(){

    System.out.println("dog eat...");

    super.setHealth(getHealth()+3);

    }

     

    /*

     *  玩飞盘

     * 狗狗的健康值-10

     * 可爱值 +5

     *

     */

     

    public void catchingFlyingDisks(){

    System.out.println("狗狗和主人玩劫飞盘的游戏");

    super.setHealth(super.getHealth()-10);

    super.setLove(super.getLove()+5);

    }

     

    }

     

    package test3;

    public class Penguin extends Pet{

    private String gender;

    /*

     * get.set

     *

     * */

    public String getGender() {

    return gender;

    }

     

    public void setGender(String gender) {

    this.gender = gender;

    }

     

    /*

      *

      * 带参数的方法

      *

      * */

    public Penguin(String name, int love, int health, String gender) {

    super(name, love, health);

    this.gender = gender;

    }

     

    /*

      *

      * 不带参数的方法

      *

      * */

    public Penguin() {

    super();

    // TODO Auto-generated constructor stub

    }

    //重写

    @Override

    public void print() {

    System.out.println("name="+super.getName()+"love="+super.getLove()+"health="+super.getHealth()+"strain="+gender);

     

    }

     

    @Override

    public void eat(){

    System.out.println("penguin eat...");

    super.setHealth(super.getHealth()+3);

    }

     

    /*

     *

     * 游泳

     *

     * */

    public void swimming(){

    System.out.println("企鹅和主人一起游泳");

    super.setHealth(super.getHealth()-20);

    super.setLove(super.getLove());

     

    }

    }

     

     

    package test3;

    public abstract class Pet {

     

    /*宠物类*/

    private String name;

    private int love;

    private int health;

     

    //默认访问权限

    int num;

     

    /*

     * get.set

     *

     * */

    public String getName() {

    return name;

    }

    public void setName(String name) {

    this.name = name;

    }

    public int getLove() {

    return love;

    }

    public void setLove(int love) {

    this.love = love;

    }

    public int getHealth() {

    return health;

    }

    public void setHealth(int health) {

    this.health = health;

    }

     

     

     /*

      *

      * 带参数的方法

      *

      * */

    public Pet(String name, int love, int health) {

    super();

    this.name = name;

    this.love = love;

    this.health = health;

     

    }

     

     

    /*

     *

     *

     * 不带参数的方法

     *

     * */

    public Pet() {

    super();

     

    // TODO Auto-generated constructor stub

    }

     

     

     

     

     

     

    /*

     *

     * 打印print

     *

     * */

     

    /*public void print(){

    System.out.println("name="+name+"love"+love+"health"+health);

    }* / 

    @Override

    public String toString() {

    return "Pet [name=" + name + ", love=" + love + ", health=" + health

    + ", num=" + num + "]";

    }

    /*抽象方法*/

    public abstract void print();

     

        //多态

    public abstract void eat();

     

    }

     

     

    package test3;

    public class Test {

    public static void main(String[] args) {

        Master m=new Master();

        Pet p1=new Dog("aa",100,100,"土狗");

        Pet p2=new Penguin("q",30,30,"");

        m.play(p1);

        System.out.println(p1.toString());

    }

    }

    心得:public void play(Pet pet)   实现父转子的一个实现

        主人有一个独特的方法-玩,宠物有独特的方法游泳、接飞盘。主人可以和狗狗玩或者企鹅玩,但是它们属于子类中定义的,不是父类中定义的也不是子类重写父类的,不能够直接调用,需要把pet转为dog/penguin

    8.总结

    1-多态可以减少类中代码量,可以提高代码的可扩展性和可维护性

    2-向上转型——子类转换为父类,自动进行类型转换

    3-向下转型——父类转换为子类,结合instanceof运算符进行强制类型转换

    4-实现多态的两种方式

    使用父类作为方法形参实现多态

    使用父类作为方法返回值实现多态

     

    练习:租车

    训练要点:

    1.多态的使用

    2.使用父类类型作为方法参数

    需求说明:

    1.在前面汽车租赁系统的基础上,实现计算多种车辆总租金的

    功能

    2.现在有客户租用

    2辆宝马

    1辆别克商务舱

    1辆金龙(34)座

    5天共多少租金?

     

    package two;

    public abstract class MotorVehicle {

    private String no;

    private String brand;

    private String color;

    private String mileage;

     

    public MotorVehicle(String no, String brand, String color, String mileage) {

    super();

    this.no = no;

    this.brand = brand;

    this.color = color;

    this.mileage = mileage;

    }

     

     

    public MotorVehicle() {

    super();

    // TODO Auto-generated constructor stub

    }

     

     

    public String getNo() {

    return no;

    }

    public void setNo(String no) {

    this.no = no;

    }

    public String getBrand() {

    return brand;

    }

    public void setBrand(String brand) {

    this.brand = brand;

    }

    public String getColor() {

    return color;

    }

    public void setColor(String color) {

    this.color = color;

    }

    public String getMileage() {

    return mileage;

    }

    public void setMileage(String mileage) {

    this.mileage = mileage;

    }

     

    /*

     * 計算租賃價格、

     * */

    public abstract double calcRent(int days);

     

     

       }

     

     

    package two;

    public final class Bus extends MotorVehicle{

    private int  seatCount;

    public int getSeatCount() {

    return seatCount;

    }

     

    public void setSeatCount(int seatCount) {

    this.seatCount = seatCount;

    }

     

    public Bus(String no, String brand, String color, String mileage,

    int seatCount) {

    super(no, brand, color, mileage);

    this.seatCount = seatCount;

    }

     

    public Bus() {

    super();

    // TODO Auto-generated constructor stub

    }

     

     

        /*

         *

         * 客车租赁价格

         *

         *

         * */

    @Override

    public double calcRent(int days) {

            double rent=0;

            int seat=this.seatCount;

            if(seat<16) {

             rent=800*days;

            }else {

             rent=1500*days;

            }

    return rent;

    }

    }

     

     

     

     

    package two;

    /*

     * 小轿车

     * final不可以被继承

     *

     * */

     

    public final class  Car extends MotorVehicle{

    private String type;

    public String getType() {

    return type;

    }

     

    public void setType(String type) {

    this.type = type;

    }

     

    public Car(String no, String brand, String color, String mileage,

    String type) {

    super(no, brand, color, mileage);

    this.type = type;

    }

     

    public Car() {

    super();

    // TODO Auto-generated constructor stub

    }

     

    /*

     * 小轎車租賃方法

     * */

    @Override

    public double calcRent(int days) {

            double rent=0;

            String type=this.type;

            if(type.equals("550i")) {

             rent=500*days;

            }else if(type.equals("別克商務艙GL8")) {

             rent=600*days;

            }else if(type.equals("別克林蔭大道")) {

             rent=300*days;

            }

    return rent;

    }

    }

     

     

     

     

     

    package two;

    /*

     * 客戶類

     * */

    public class Customer {

     

     private String name;

     private String no;

    public Customer(String name, String no) {

    super();

    this.name = name;

    this.no = no;

    }

    public Customer() {

    super();

    // TODO Auto-generated constructor stub

    }

    public String getName() {

    return name;

    }

    public void setName(String name) {

    this.name = name;

    }

    public String getNo() {

    return no;

    }

    public void setNo(String no) {

    this.no = no;

    }

    /*

     * 計算客戶租車縂租金

     * */

    public double calcTotalRent(MotorVehicle[] motos,int days) {

      double rent=0;

      for (int i = 0; i < motos.length; i++) {

            rent+=motos[i].calcRent(days);

      }

      return rent;

    }

    }

     

     

    package two;

    public class Test {

        public static void main(String[] args) {

         MotorVehicle[] motos=new MotorVehicle[5];

         motos[0]=new Car("A12345","宝马","red","5w","550i");

         motos[1]=new Car("A12346","别克","red","10w","550i");

         motos[2]=new Car("A12347","别克","red","15w","550i");

         motos[3]=new Bus("A12348","金龙","red","5w",20);

         motos[4]=new Truck("A12349","金杯","red","5w",10);

        

         int days=10;

         Customer c=new Customer();

         double rent=c.calcTotalRent(motos, days);

            System.out.println("5辆车的总租金"+rent);

    }

    }

     

     

     

    心得:  先写一个父类,之后写俩个子类

    然后写一个客户类customer,写入计算总租金的方法

          Carbus分别写入各自的计算方法。

     

    练习:购置新车

    1.训练要点:

    使用父类作为方法形参实现多态

    使用多态增强系统的扩展性和可维护性

    2.需求说明:

    新购置了卡车,根据吨位,租金每吨每天50

    对系统进行扩展,计算汽车租赁的总租金

     

     

    package two;

    public class Truck extends MotorVehicle {

     

    private  int ton;

     

    public int getTon() {

    return ton;

    }

     

    public void setTon(int ton) {

    this.ton = ton;

    }

     

    public Truck(String no, String brand, String color, String mileage, int ton) {

    super(no, brand, color, mileage);

    this.ton = ton;

    }

     

     

    @Override

    public double calcRent(int days) {

    double rent=0;

    rent=50*days*days*this.ton;

    return rent;

    }

    }

    练习:披萨

    package lx1;

    //披薩

    public abstract class Pizza {

     

     private String name;

     private double price;

     private String size;

    public Pizza(String name, double price, String size) {

    super();

    this.name = name;

    this.price = price;

    this.size = size;

    }

    public Pizza() {

    super();

    // TODO Auto-generated constructor stub

    }

    public String getName() {

    return name;

    }

    public void setName(String name) {

    this.name = name;

    }

    public double getPrice() {

    return price;

    }

    public void setPrice(double price) {

    this.price = price;

    }

    public String getSize() {

    return size;

    }

    public void setSize(String size) {

    this.size = size;

    }

    //製作

    public abstract  void make();

    }

     

     

     

    package lx1;

     

    public class BaconPizza extends Pizza {

     

      private String kilo;

     

    public BaconPizza(String name, double price, String size, String kilo) {

    super(name, price, size);

    this.kilo = kilo;

    }

     

    public BaconPizza() {

    super();

    // TODO Auto-generated constructor stub

    }

     

    public String getKilo() {

    return kilo;

    }

     

     

    public void setKilo(String kilo) {

    this.kilo = kilo;

    }

     

    @Override

    public void make() {

    // TODO Auto-generated method stub

    System.out.println("name="+super.getName());

    System.out.println("price="+super.getPrice());

    System.out.println("size="+super.getSize());

    System.out.println("kilo="+kilo);

    }

    }

     

     

     

    package lx1;

     

    public class SeafoodPizza extends Pizza {

     

     private String ingredient;

     

    public SeafoodPizza(String name, double price, String size, String ingredient) {

    super(name, price, size);

    this.ingredient = ingredient;

    }

     

    public SeafoodPizza() {

    super();

    // TODO Auto-generated constructor stub

    }

     

    public String getIngredient() {

    return ingredient;

    }

     

    public void setIngredient(String ingredient) {

    this.ingredient = ingredient;

    }

     

    @Override

    public void make() {

    // TODO Auto-generated method stub

    System.out.println("name="+super.getName());

    System.out.println("price="+super.getPrice());

    System.out.println("size="+super.getSize());

    System.out.println("ingredient="+ingredient);

    }

    }

     

     

     

     

    package lx1;

    public class PizzaFactory {

     /*

      *

      * 工厂

      *

      * */

    public void makePizza(Pizza pizza) {

    pizza.make();

    }

    }

     

     

     

    package lx1;

    public class Test {

    public static void main(String[] args) {

      PizzaFactory pf=new PizzaFactory();

      Pizza baconpizza=new BaconPizza("培根", 100, "9", "500g");

      Pizza seafoodpizza=new SeafoodPizza("海鲜", 100, "9", "蝦仁 鱿鱼卷 墨鱼");

      pf.makePizza(baconpizza);

      System.out.println("***************");

      pf.makePizza(seafoodpizza);

      

    }

    }

  • 相关阅读:
    Best Cow Fences_二分&&DP
    Palindrome_滚动数组&&DP
    Making the Grade_滚动数组&&dp
    BUY LOW, BUY LOWER_最长下降子序列
    Testing the CATCHER_DP
    Best Sequence_DFS&&KMp
    (Your)((Term)((Project)))
    [SOJ] 畅通工程续
    [SOJ] 商人的宣传
    [SOJ] 无路可逃?
  • 原文地址:https://www.cnblogs.com/-lyr/p/9597277.html
Copyright © 2011-2022 走看看