1. 程式人生 > 其它 >JAVA面向物件程式設計第八章-第九章課後習題答案--------面向物件中的多型+使用異常處理

JAVA面向物件程式設計第八章-第九章課後習題答案--------面向物件中的多型+使用異常處理

技術標籤:java學習介面eclipsejava多型

第八章

1、要使程式執行出下面結果,修改程式

package com.xiujie.part_8;

public class T01 {
	public static void main(String[] args) {
		Person person=new Person("小明",'男');
		person.show();
		Student student=new Student("小明",'男',101);
		student.show();
		Pupil pupil=new Pupil
("小明",'男',101,95); pupil.show(); } } class Person{ String name; char sex; public Person() {} Person(String n,char s){ name=n; sex=s; } void show() { System.out.println("name is"+name+",sex is "+sex); } } class Student extends Person{ int number; public Student
() {} public Student(String n,char s,int num) { name=n; sex=s; number=num; } void show() { System.out.println("name is "+name+",sex is "+sex+",number is "+number); } } class Pupil extends Student{ double hcScore; public Pupil() {} public Pupil(String n,char
s,int num,double hcs) { name=n; sex=s; number=num; hcScore=hcs; } void show() { System.out.println("name is"+name+",sex is "+sex+",number is "+number+",score is "+hcScore); } }

提示:要想實現pupil繼承student,需要把final去掉,final修飾的方法是不可變的,不允許後期的修改。

執行結果:

在這裡插入圖片描述
2、求正方形面積
1)建立介面IShape
2)定義類square,實現IShape介面,square類有一個屬性表示正方形邊長,構造方法初始化邊長
3)定義一個主類,在此類中建立square類的例項,求該正方形面積

package com.xiujie.part_8;

public class Getzheng {
	public static void main(String[] args) {
		square sq=new square(6);
		System.out.println("正方形面積是"+sq.area());
	}
}
class square implements IShape{
	double b;//邊長
    public square(double bian) {
    	b=bian;
    }
	@Override
	public double area() {
		return b*b;
	}
	
}
interface IShape{
	public double area();
}

執行結果
在這裡插入圖片描述

第九章

1、大家也可以舉其他例子哈在這裡插入圖片描述
2、詢問使用者是哪個年紀的同學,對輸入的資料進行儲存,將結果顯示在螢幕上

package com.xiu.part_9;
import java.util.Scanner;

public class Try {
	public static void main(String[] args) throws GradeException {
		System.out.println("你是幾年級的同學?");
		Scanner scanner = new Scanner(System.in);
		int i = scanner.nextInt();
		if (i >= 1 && i <= 3) {
			System.out.println("你是" + i + "年級的同學!");
		} else {
			throw new GradeException("輸入了不存在的年級!");
		}
		scanner.close();
	}
}
class GradeException extends Exception {
	public GradeException(String string) {
		super(string);
	}
}

執行結果

1)輸入存在的年級
在這裡插入圖片描述
2)輸入不存在的年級
在這裡插入圖片描述