本文目錄一覽:
java實驗題目,關於多態,接口
interface EqualDiagonal {
double getDiagonal();
}
class Rectangle1 implements EqualDiagonal {
private double a;
private double b;
public Rectangle1(double d,double e){
this.a=d;
this.b=e;
}
public Rectangle1(){
}
public double getDiagonal() {
return Math.sqrt(a * a + b * b);
}
}
class Square extends Rectangle1 implements EqualDiagonal {
private double a;
public Square(int x){
this.a=x;
}
public double getDiagonal() {
return Math.sqrt((2.0) * a * a);
}
}
public class Hypotenuse {
public static void main(String[] args) {
Rectangle1 c = new Rectangle1(5.0,6.0);
Square b = new Square(5);
System.out.println(“長方形的斜邊長是:” + c.getDiagonal());
System.out.println(“正方形的斜邊長是:” + b.getDiagonal());
}
}
Java關於繼承、多態(接口和包)的編程題
package animal.mammal;
// 狗類
public class Dog extends Mammal{
void speak(){
System.out.println(“Woof!”);
}
void yaoweiba(){
System.out.println(“Tail wagging…”);
}
void qitaoshiwu(){
System.out.println(“begging for food…”);
}
}
// 同理寫貓,馬,豬,其中都必須有方法 void speak() 輸出各不相同,其他方法自定義
public class Cat extends Mammal{
}
public class Horse extends Mammal{
}
public class Pig extends Mammal{
}
// 另外是寵物貓,寵物狗的
package animal.mammal.pet;
public class PetCat extends Cat{
doucle price = 40.00;
String ownername = peter;
void Price(){
System.out.println(“PetCat price:” + this.price);
}
void Owner(){
System.out.println(“this’s ” + this.ownername +” petCat”);
}
}
// 同理寫寵物狗的,如果需要 get/set 則為 price,ownername 加上該方法
public class PetDog extends Dog{
}
JAVA多態經典例題
System.out.println(“1–” + a1.show(b));
a1是A類引用指向A類對象,不存在多態,一定調用A類方法。A類方法有兩個show(D)和show(A),b是B類引用無法轉換為D類引用,但可以轉換為A類引用,因此調用show(A),輸出A and A。
System.out.println(“2–” + a1.show(c));
輸出A and A,原因同上。
System.out.println(“3–” + a1.show(d));
調用show(D),輸出A and D。
System.out.println(“4–” + a2.show(b));
a2是A類引用指向B類對象,可能存在多態。b是B類引用無法轉換為D類引用,但可以轉換為A類引用,因此調用show(A),而B類重寫了show(A),因此調用的是重寫後的show(A),輸出B and A。
System.out.println(“5–” + a2.show(c));
同上,C類引用無法轉換為D類引用,但可以轉換為A類引用,因此調用show(A),輸出B and A。
System.out.println(“6–” + a2.show(d));
調用show(D),show(D)又調用父類即A類的show(D),輸出A and D
System.out.println(“7–” + b.show(b));
b是B類引用指向B類對象,不存在多態,一定調用B類方法。B類一共有三個方法:重寫自A類的show(A)和show(D),以及新定義的show(B)。show(b)調用show(B)方法,輸出B and B
System.out.println(“8–” + b.show(c));
C類繼承自B類,也調用show(B)方法,輸出B and B
System.out.println(“9–” + b.show(d));
調用show(D),show(D)又調用父類即A類的show(D),輸出A and D
用接口和多態的知識實現一道JAVA題,主要是實現接口
sum += (CalcArea)shapes[i].getArea();
錯誤有兩個
1、 轉型應該是sum += ((CalcArea)shapes[i]).getArea();
2、getArea()這個方法死沒有定義的 因為你的接口中只有getArea(double r)和getArea(double length, double width)
原創文章,作者:K6GCB,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/127912.html