子承父类

来源:互联网 发布:js 数组存在值 编辑:程序博客网 时间:2024/06/05 17:17

面向对象的三大特征:封装、继承、多态

封装是隐藏对象内部的复杂性,只对外公开简单的接口,便于外界调用,提高系统的可扩展性可维护性。

继承需要extends关键字来实现,Java中只有单继承,没有像c++中那样的多继承,(但在接口中又能实现多继承)

多态包括重载和 重写,多态实现了代码的多样化

多态存在的必要条件是:1.要有继承,2.要有方法重写,3.父类引用指向子类对象

理论要有,代码还是要敲得

二、

编写程序实现比萨制作。需求说明编写程序,接收用户输入的信息,选择需要制作的比萨。可供选择的比萨有:培根比萨和海鲜比萨。
实现思路及关键代码
1)    分析培根比萨和海鲜比萨
2)    定义比萨类
3)    属性:名称、价格、大小
4)    方法:展示
5)    定义培根比萨和海鲜比萨继承自比萨类
6)    定义比萨工厂类,根据输入信息产生具体的比萨对象

package com.zy;

/**
 * 披萨类
 * @author ren
 *
 */
public abstract class Pizzas {
    String name;
    int price;
    int size;
    //全参构造方法
    public Pizzas(String name,int price,int size){
        this.name=name;
        this.price=price;
        this.size=size;
    }
    public abstract void show();
}

package com.zy;

/**
 * 培根披萨类
 * @author ren
 *
 */
public class BaconPizza extends Pizzas {
    int height;
    
    public BaconPizza(int height,String name, int price, int size) {
        super(name, price, size);
        this.height=height;    
    }

    @Override
    public void show() {
        System.out.println("名称:"+name+"\n价格:"+price+"\n大小:"+size+"\n培根克数:"+height);
        
    }
    
}

package com.zy;

/**
 * 海鲜披萨类
 * @author ren
 *
 */
public class SeafoodPizza extends Pizzas {
    String fish;
    String xia;
    public SeafoodPizza(String fish,String xia,String name, int price, int size) {
        super(name, price, size);
        this.fish=fish;
        this.xia=xia;
        
    }

    @Override
    public void show() {
        System.out.println("名称:"+name+"\n价格:"+price+"\n大小:"+size+"\n配料:"+fish+"、"+xia);
        
    }

}

package com.zy;

import java.util.*;

public class Factory {
    
    public static void main(String[] args) {
        System.out.println("请选择要制作的披萨(1.培根披萨2.海鲜披萨)");
        Scanner sc=new Scanner(System.in);
        int a=sc.nextInt();
        if(a==1){
            Scanner s=new Scanner(System.in);
            System.out.println("请输入培根克数:");
            int height=s.nextInt();
            System.out.println("请输入披萨大小:");
            int size=s.nextInt();
            System.out.println("请输入披萨价格:");
            int price=s.nextInt();
            BaconPizza b=new BaconPizza(height, "培根披萨", price, size);
            b.show();
        }else if(a==2){
            Scanner s1=new Scanner(System.in);
            System.out.println("请输入配料:");
            String fish=s1.next();
            String xia=s1.next();
            System.out.println("请输入披萨大小:");
            int size=s1.nextInt();
            System.out.println("请输入披萨价格:");
            int price=s1.nextInt();
            SeafoodPizza s=new SeafoodPizza(fish,xia, "海鲜披萨", price, size);
            s.show();
        }
    }
}