当前位置:首页 > 期末复习题
}
public static void main(String[] args) {
Student s1=new Student(\,\男\,20,'A'); s1.print();
}
7.定义一个类Rectangle代表矩形,其中包括计算面积的方法。再定义一个它的子类Square代表正方形],其中也包含计算面积的方法。编写一程序,测试新建子类对象的属性和方法? class Rectangle{ float length; float width; Rectangle(float len,float wh){ length=len; width=wh; } float getArea(){ return length*width; } }
class Square extends Rectangle{ float length; Square(float len){ super(len,len); length=len; } float getArea(){ return super.getArea(); } }
public class TestRectangle{ public static void main(String[] args){ Square sq=new Square(5.2f); System.out.println(\ } } 8.定义一个Document类,包含成员属性name。从Document派生出Book子类,增加PageCount变量,编写一应用程序,测试定义的类? class Document{ String name; Document(String str){ name=str; }
21
void show(){ System.out.println(name); } }
class Book extends Document{ int PageCount; Book(String name,int n){ super(name); PageCount=n; } void show(){ System.out.print(\ super.show(); System.out.println(\ } }
public class TestDoc{ public static void main(String[] args){ Book book1=new Book(\ book1.show(); } }
9.编写一个Java应用程序,设计一个汽车类Vehicle,包含的属性有车轮个数wheels和车重weight。小车类Car是Vehicle的子类,其中包含的属性有载人数loader。卡车类Truck是Car类的子类,其中包含的属性有载重量payload。每个类都有构造方法和输出相关数据的方法。 class Vehicle { int wheels; float weight;
Vehicle(int wh,float we) { wheels=wh; weight=we;
}
int getWheels(){return wheels;} float getWeight(){return weight;} void show() {
System.out.println(“车轮:”+wheels); System.out.println(“车重:”+weight); } }
class Car extends Vehicle {
int loader;
22
Car(int wheels,float weight,int loader) {super(wheels,weight); this.loader=loader;} }
public void show() {
System.out.println(“车型:小车”); super.show();
System.out.println(“载人:”+loader); }
class Truck extends Car {
float payload;
Truck(int wheels,float weight,int loader,float payload) {super(wheels,weight,loader); this.payload=payload;} }
public void show() {
System.out.println(“车型:卡车”); super.show();
System.out.println(“载重量:”+payload); }
public class VehicleClient {
public static void main(String[] args) {
Car car=new Car(4,1500,4); car.show();
Truck truck=new Truck(8,7000,3,25000); truck.show(); } }
10.一个关于等边三角形的类Trival如下,其中的属性包括三角形的bian,方法包括:默认构造方法、为bian指定初值的构造方法、获取三角形面积findArea()。试利用方法覆盖的知识,设计三棱柱体类TriCylinder。(其中findArea()为计算三棱柱体的表面积) class Trival { double bian; Trival() { bian=1.0; } Trival(double b)
23
{ bian=b; }
double findArea() {
return (3/4)*bian*bian;
} }
答案:
public class TestOverrideMethods {
public static void main(String[] args) {
Cylinder myTriCylinder = new TriCylinder(5.0, 2.0);
System.out.println(\ System.out.println(\ System.out.println(\ myTriCylinder.findArea()); } }
class TriCylinder extends Trival {
private double length;
// Default constructor public Cylinder() {
super(); length = 1.0; }
public Cylinder(double r, double l) {
super(r); length = l; }
// Getter method for length public double getLength() {
return length;
24
共分享92篇相关文档