Java第五次作业 李新磊

Java第五次作业--面向对象高级特性(抽象类和接口)

(一)学习总结

1.在上周完成的思维导图基础上,补充本周的学习内容,对Java面向对象编程的知识点做一个全面的总结。

2.汽车租赁公司,出租汽车种类有客车、货车和皮卡三种,每辆汽车除了具有编号、名称、租金三个基本属性之外,客车有载客量,货车有载货量,皮卡则同时具有载客量和载货量。用面向对象编程思想分析上述问题,将其表示成合适的类、抽象类或接口,说明设计思路并画出类图。

设计思路

设计一个汽车抽象类,包含三种共有属性:编号、名称、租金;
设计两个接口:载客接口包含显示载客数方法,载货接口包含显示载货数方法;
设计三种汽车类:客车、货车、皮卡,三种汽车都继承汽车抽象类;其中客车继承载客接口,货车继承载货接口,皮卡继承载货和载客接口。

3.阅读下面程序,分析代码是否能编译通过,如果不能,说明原因,并进行改正。如果能,列出运行结果

    interface Animal{    
        void breathe();
        void run();
        void eat();
    }
    class Dog implements Animal{
        public void breathe(){
            System.out.println("I'm breathing");
        }
        void eat(){
            System.out.println("I'm eating");
        }
    }
    public class Test{
        public static void main(String[] args){
            Dog dog = new Dog();
            dog.breathe();
            dog.eat();
        }
    }

不能通过,Dog类继承Animal接口,Dog类必须实现接口的抽象所有方法

接口的抽象方法默认为public权限,实现接口的类中覆写的抽象方法必须写public

修改后

interface Animal{    
    void breathe();
    void run();
    void eat();
}
class Dog implements Animal{
    public void breathe(){
        System.out.println("I'm breathing");
    }
    public void eat(){
        System.out.println("I'm eating");
    }
	@Override
	public void run() {
		 System.out.println("I'm running");
		
	}
}
public class Test{
    public static void main(String[] args){
        Dog dog = new Dog();
        dog.breathe();
        dog.eat();
        dog.run();
    }
}

运行结果

I'm breathing
I'm eating
I'm running

4.运行下面的程序

    import java.util.Arrays;
    public class Test{
        public static void main(String[] args){
            String[] fruits = {"peach","banana","orange","apple"};
            Arrays.sort(fruits);
            for(int i = 0;i < fruits.length;i++)
            {
                System.out.println(fruits[i]);
            }
        }
    }

String源码

public final class String implements java.io.Serializable, Comparable<String>, CharSequence {
private final int offset;
private final int count;
public String() {
    this.offset = 0;
    this.count = 0;
    this.value = new char[0];
}
public String(String original) {
    int size = original.count;
    char[] originalValue = original.value;
    char[] v;
    if (originalValue.length > size) {
        int off = original.offset;
        v = Arrays.copyOfRange(originalValue, off, off+size);
    } else {
        v = originalValue;
    }
    this.offset = 0;
    this.count = size;
    this.value = v;
}

定义一个新的String对象时(写String类的有参构造时),定义一个新的String对象original,声明新数组originalValue,排序时,如果originalValue长度大于original对象的count(当字符串大于新的字符串original)时,对originalValue排序,排序后数组给新数组v;如果不大于,代表两个代表字符串的数组相同

逆序输出 修改后

import java.util.Arrays;
public class Test{
    public static void main(String[] args){
        String[] fruits = {"peach","banana","orange","apple"};
        Arrays.sort(fruits);
        for(int i = fruits.length-1;i >= 0;i--)    
        {
            System.out.println(fruits[i]);
        }
    }
}

(二)实验总结

1.音乐盒

程序设计思路

设计一个MusicBox接口,Pianobox类、ViolinBox类继承MusicBox接口;
设计一个MusicBoxFactory类,作为过渡端,在过渡端中创建音乐盒对象,将创建对象的具体过程屏蔽隔离起来。

问题1.工厂设计模式的实现

设计一个MusicBoxFactory类,作为过渡端;在主方法中输入想要创建的对象,作为参数传递给MusicBoxFactory类的getInstance方法,根据输入,创建相应对象。

public class MusicBoxFactory {
	public static MusicBox getInstance (String className){
		MusicBox box = null;
		if("PianoBox".equals(className)){    //创建PianoBox对象
			box=new PianoBox();
		}
		if("ViolinBox".equals(className)){    //创建ViolinBox对象
		 box=new ViolinBox();
		}
		return box;
	}
	public static void main(String[] args) {
			Scanner in= new Scanner(System.in);
			System.out.println("What Music Box do you want?");
			String input=in.next();
			MusicBox box=MusicBoxFactory.getInstance(input);
			if(box!=null){
				box.play();
			}
	}

}

2.职工信息按照生日排序

程序设计思路

将员工生日和工作日期设为Date类,employee类的构造方法设为employee(String name,int id,String sex,Date birthday,Date workTime),在employee类对象实例化时输入日期等信息;分别用Comparator、Comparatable接口把empolyee类的对象数组按照出生日期排序

问题1.Date类的使用

将工作日期和出生日期设为Date类,输入日期时,输入“yyyy-MM-dd”格式的字符串,再将字符串转换为Date类储存

SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");        //指定格式化日期模板“yyyy-MM-dd”
Date date={sdf.parse("1996-11-17");                            //将字符串转换成Date对象
employee[] worker={new employee("Tom",1001,"男",date,date)};    //实例化对象

输出日期时,将Date类转换为字符串输出

public String getBirthday(){
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); //指定格式化日期模板“yyyy-MM-dd”
		String str=sdf.format(birthday);                //将Date对象转换成字符串
		return str;                                    //输出字符串
	} 

问题2.Comparator、Comparatable接口的使用

运用Comparable接口,在employee方法中编写compareTo(employee o)方法,按照出生日期进行排序

public class employee implements Comparable<employee> {
	 Date  birthday;
	 ......
	public employee(...... Date workTime){
		......
		this.birthday=birthday;
	}
		

	public int compareTo(employee o) {
		if(this.birthday.getTime()>o.birthday.getTime()){
		return 1;
		}else if(this.birthday.getTime()<o.birthday.getTime()){    //获取出生日期,运用getTime()方法,将当前对象的日期与对象o的日期进行比较
			return -1;
			}
		else{
			return 0;
		}
	}
	
}

新建一个EmployeeComparator方法,继承Comparator接口,按照出生日期进行排序

import java.util.Comparator;
public class EmployeeComparator implements Comparator<employee>{

	public int compare(employee o1, employee o2) {
		if(o1.getBirthday1().getTime()>o2.getBirthday1().getTime()){            //比较对象o1的日期与对象o2的日期
				return 1;
			}else if(o1.getBirthday1().getTime()<o2.getBirthday1().getTime()){
				return -1;
			}else {
				return 0;
				}
		}
	

}
Arrays.sort(worker);                              //sort方法(Comparable接口)
Arrays.sort(worker,new EmployeeComparator());    //sort方法(Comparator接口)

3.宠物商店

程序设计思路

设计一个Pet接口、Dog类和Cat类,Dog、Cat类继承Pet接口;
设计一个PetShop类,内含宠物商店的操作方法,add(): 添加宠物方法,seach(): 查找宠物方法,kind(): 统计用户购买宠物方法;
设计一个user类,实现用户购买过程

问题1.宠物商店的设计模式及宠物商店的操作方法

定义一个Pet接口,接口中只有取得宠物信息的方法,因此可以添加任意类型的宠物,本题只有Dog类和Cat类

public interface Pet {
	public int getId();
	public String getKind();
	public String getColour();
	public int getPrice();
}
public class Dog implements Pet{ ...}
public class Cat implements Pet{ ...}

PetShop()类中,包含向商店添加宠物方法,根据编号查找宠物信息方法

public class PetShop {
	Pet[] pets;
	private int foot;
	public PetShop(int len){
		if(len>0){
			this.pets=new Pet[len];    //构造方法,根据设定长度开辟宠物数组,大小至少为1
		}else{
			this.pets=new Pet[1];
		}
	}
	public boolean add(Pet pet){
		if(this.foot<this.pets.length){
			this.pets[this.foot]=pet;    //增加宠物,foot判断数组是否已满
			this.foot++;
			return true;
		}else{
			return false;
		}
	}
	public Pet search(int id){
		for(int i=0;i<this.pets.length;i++){
			if(id==this.pets[i].getId()){    //根据宠物编号查找宠物信息
				return this.pets[i];
			}
		}
		return null;
	}
......
}

问题2.用户购买过程的实现及统计用户购买清单

设计一个购买方法buy(),递归调用自身

每次购买宠物时,调用searchPrice()方法,输出宠物信息;
在购买结束后,输出购买清单:总金额,猫的金额、数量、品种,狗的金额,数量、品种

public static int buy(PetShop ps,int n,int CatPrice,int DogPrice,int dogNum,int catNum){
		n++;
		System.out.println("请输入购买宠物的序号");
		Scanner in=new Scanner(System.in);
		int ids=in.nextInt();
		System.out.println(ps.search(ids));
		if(ids<20&&ids!=0){
			DogPrice+=ps.searchPrice(ids);
			dogNum++;
			ps.kind(n,ids);
		}
		else if(ids>0){
			CatPrice+=ps.searchPrice(ids);
			catNum++;
			ps.kind(n,ids);
		}
		
		System.out.println("是否继续购买?y/n");
		String str=in.next();
		if(str.equals("y")){
			return buy(ps,n,CatPrice,DogPrice,dogNum,catNum);
			}else{
				System.out.println("总价格: "+(CatPrice+DogPrice)+" 狗数量: "+dogNum+" 狗价格: "+DogPrice+" 猫数量: "+catNum+" 猫价格: "+CatPrice);
				for(int i=0;i<n;i++){
					if(ps.getDogKind()[i]!=null){
						System.out.println("狗种类:"+ps.getDogKind()[i]);
					}
				}
				for(int i=0;i<n;i++){
					if(ps.getCatKind()[i]!=null){
						System.out.println("猫种类:"+ps.getCatKind()[i]);	
					}
				}
				return n;
			}
	}

每次购买宠物时,猫或狗的金额都会作为参数调用,并累加;
每次购买宠物时,猫或狗的品种都会储存到字符串数组dogKind或catKind中,购买结束后输出购买的猫和狗的品种。

System.out.println("请输入购买宠物的序号");
		Scanner in=new Scanner(System.in);
		int ids=in.nextInt();
		System.out.println(ps.search(ids));
		if(ids<20&&ids!=0){
			DogPrice+=ps.searchPrice(ids);
			dogNum++;
			ps.kind(n,ids);
		}
		else if(ids>0){
			CatPrice+=ps.searchPrice(ids);
			catNum++;
			ps.kind(n,ids);
		}

(三)代码托管

https://git.oschina.net/hebau_cs15/Java-CS02lxl/tree/master/ex05?dir=1&filepath=ex05&oid=c573a575ad5e1d084d43e545ea60316e3bb78158&sha=739b896fe9869207111d2e5c23ccb4bfb6ebece6

posted on 2017-04-21 23:11  押沙龙  阅读(457)  评论(0)    收藏  举报