{
public void setw(double weight);
pbulic double getw();
}
下面的类中直接出现
class Train
{
...
setWeight thing[]=new setWeight[i];
...
}
不解中!求助各位!
这其实就看你对多态的理解了。。这只是定义了一个数组。这个数组中可以存储任何实现setWeight接口的类。。
可能是我没有写完整吧,还是我没有理解好
1 接口
public interface SetAndGetWeight
{
public void setW(double weight);
public double getW();
}
2 类
class Train
{
SetAndGetWeight[] things;
public void Train(SetAndGetWeight[] things)
{
this.things=things;
}
public void returnTotalWeight()
{
double totalweight=0;
for(int i=0;i<things.length;i++)
{
totalweight=totalweight+things[i].getW();
}
System.out.println("Train总的质量是:"+totalweight);
}
}
第3个类
import java.util.Scanner;
class TrainComWeight
{
public static void main(String[] arg)
{
Scanner rd=new Scanner(System.in);
System.out.println("请输入船上人数:");
int peonum=rd.nextInt();
System.out.println("请输入船上Tv数:");
int tvnum=rd.nextInt();
System.out.println("请输入船上COM数:");
int comnum=rd.nextInt();
System.out.println("请输入船上wash数:");
int washnum=rd.nextInt();
int totalnum=peonum+tvnum+comnum+washnum;
SetAndGetWeight[] things=new SetAndGetWeight[totalnum];
Train tr=new Train(things);
System.out.println("请输入各个人的体重!");
for(int i=0;i<peonum;i++)
{
System.out.println("请输入第"+i+"peo的重量");
things[i].setW(rd.nextDouble());
}
System.out.println("请输入TV的重量");
for(int j=peonum;j<peonum+tvnum;j++)
{
System.out.println("请输入第"+j+"tv的重量");
things[j].setW(rd.nextDouble());
}
System.out.println("请输入COM的重量");
for(int k=peonum+tvnum;k<peonum+tvnum+comnum;k++)
{
System.out.println("请输入第"+k+"CIN的重量");
things[k].setW(rd.nextDouble());
}
System.out.println("请输入WASH的重量");
for(int l=peonum+tvnum+comnum;l<totalnum;l++)
{
System.out.println("请输入第"+l+"WASH的重量");
things[l].setW(rd.nextDouble());
}
//System.out.println(train)
}
}
其中红色的地方Train tr=new Train(things);会报错"找不到符号"