商苑面馆:Java类的继承

来自CloudWiki
Cloud17讨论 | 贡献2019年4月17日 (三) 01:55的版本 (创建页面,内容为“Food类: <nowiki> public class Food { //成员变量 //名称 private String name; //价格 private double price; //数量 private int num; /*构造方…”)
(差异) ←上一版本 | 最后版本 (差异) | 下一版本→ (差异)
跳转至: 导航搜索

Food类:

public class Food {
	//成员变量
	//名称
	private String name;
	//价格
	private double price;
	//数量
	private int num;
	
	/*构造方法*/
	public Food(){
		
	}
	public Food(String name,double price,int num){
		this.name = name;
		this.price = price;
		this.num = num;
	}
	
	//成员方法
	public String getName(){
		return this.name;
	}
	public double getPrice(){
		return this.price;
	}
	public int getNum(){
		return this.num;
	}
	//写方法
	public boolean setName(String s){
		this.name = s;
		return true;
	}
	public boolean setPrice(double p){
	    this.price = p;
	    return true;
	}
	public boolean setNum(int n){
	    this.num = n;
	    return true;
	}
	   
	public String toString(){
	    return "名称:" +this.name+"价格:"+
	               this.price + "数量: " + this.num;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}


面条类:

public class Noodle extends Food {
	
	/*构造方法*/
	public Noodle(){
		
	}
	public Noodle(String name,double price,int num){
		super(name,price,num);
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		        
        Noodle n2 = new Noodle("炸酱面",12,3);
        System.out.println("您订的面是"+n2.getName());
        System.out.println("价格:"+n2.getPrice());

        
       
        
	}

}



小吃类:


public class SmallEat extends Food{

    private String flavor;
    SmallEat(){
    	
    }
    SmallEat(String name,double price,int num){
    	super(name,price,num);
    }
public String toString(){
	    return "名称:" + getName()+"价格:"+
	               getPrice() + "数量: " + getNum() + "口味:"+ flavor;
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
        SmallEat s = new SmallEat("鹌鹑蛋",3,2);
        System.out.println(s.toString());
	}

}