继承上机作业

1、实现如下类之间的继承关系,并编写Music类来测试这些类。
package qwe;
class Instrument {
public void play () {
System.out.println("弹奏乐器:");
}
}
class Wind extends Instrument {
public void play () {
System.out.println("弹奏Wind");
}
public void play2 (){
System.out.println("调用wind的play2");
}

}

class Brass extends Instrument {
public void play () {
System.out.println("弹奏Brass");
}
public void play2 () {
System.out.println("调用brass的play2");
}
}
public class Music {
public static void tune (Instrument i) {
i.play();
}
public static void main(String[] args) {
Music mm = new Music();
Wind w = new Wind();
Brass b = new Brass();
mm.tune(b);
mm.tune(w);
}
}
2、编写一个Java应用程序,该程序包括3个类:Monkey类、People类和主类E。要求:

(1) Monkey类中有个构造方法:Monkey (String s),并且有个public void speak()方法,在speak方法中输出“咿咿呀呀......”的信息。

(2)People类是Monkey类的子类,在People类中重写方法speak(),在speak方法中输出“小样的,不错嘛!会说话了!”的信息。

(3)在People类中新增方法void think(),在think方法中输出“别说话!认真思考!”的信息。

(4)在主类E的main方法中创建Monkey与People类的对象类测试这2个类的功能。

package qwe;

public class Monkey {
Monkey(String s ){
}
public Monkey() {

}
public void speak() {
System.out.println("咿咿呀呀......");
}
public class People extends Monkey{
People(String s){
super(s);
}
public People() {
}
public void speak() {
System.out.println("小样的,不错嘛!会说话了!");
}
public void think() {
System.out.println("别说话!认真思考!");
}
}
public class E {
public static void main(String[] args) {
Monkey m=new Monkey();
People p=new People();
m.speak();
p.speak();
p.think();
}
}
}
3、按要求编写一个Java应用程序:

(1)定义一个类,描述一个矩形,包含有长、宽两种属性,和计算面积方法。

(2)编写一个类,继承自矩形类,同时该类描述长方体,具有长、宽、高属性,和计算体积的方法。

(3)编写一个测试类,对以上两个类进行测试,创建一个长方体,定义其长、宽、高,输出其底面积和体积。
package qwe;
import java.util.Scanner;
class Rectangle{
private double length;
private double width;
public double getLength(){
return length;
}
public double getWidth(){
return width;
}
public Rectangle(double length, double width){
this.length = length;
this.width = width;
}
public double getArea(){
return lengthwidth;
}
}
class Cuboid extends Rectangle{
private double height;
public double getHeight() {
return height;
}
public Cuboid(double length, double width, double height){
super(length, width);
this.height = height;
}
public double getVolume(){
return getLength()
getWidth()*height;
}
}
package qwe;
import java.util.Scanner;
public class Test{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
System.out.println("请分别输入长方形的长、宽:");
Rectangle rc=new Rectangle(sc.nextDouble(),sc.nextDouble());
System.out.println("长方形的面积为:"+rc.getArea()); System.out.println();
System.out.println("请分别输入长方体的长、宽、高:");
Cuboid cb=new Cuboid(sc.nextDouble(),sc.nextDouble(),sc.nextDouble()); System.out.println("长方体的底面积为:"+cb.getArea()); System.out.println("长方体的体积为:"+cb.getVolume());
}
}

原文地址:https://www.cnblogs.com/6825186a/p/10850064.html