我希望在更改子类中的实例变量的值后,使用超类实例变量作为超类方法中的参数

时间:2014-04-02 06:40:14

标签: java inheritance polymorphism

我是java的新手,我想在超类中声明实例变量,然后在子类中更改它们的值,然后在超类的方法中使用这些实例变量作为参数,但实例变量的值不是改变。请解释我怎么做!!!!!!

    abstract class Crop {
boolean yieldFlower;
String ColorOfFlower;
public boolean isUseful;       
public String[] Products1;

public void eat() {
System.out.println("it consumes sunlight , minerals , water etc");
System.out.println(isUseful); 
}

public void theyGrow(){
System.out.println("they grow slowly but steadily");
}

public void theyRemainStill(){
System.out.println("they do not move");
}

public void ReleaseCarbonDioxide() {
System.out.println("they release CarbonDioxide");
}

public abstract void FavourableSeason();


public void UsefulProducts(String[] Products2){
for(String a:Products2){
System.out.println("One of it's useful product is " + a );
} 
}
}

abstract class Kharif extends Crop {
public void FavourableSeason() {
System.out.println("it is grown in rainy season ");
}
}

abstract class Rabi extends Crop {
public void FavourableSeason() {
System.out.println("it is grown in winter season");
}
}

class millets extends Kharif {

boolean YieldFlower =false;

boolean isUseful=true;    //value of isUseful changed to true

String[] Products1={"food","food","food"}; //values of arrays defined

}

class cotton extends Kharif {

boolean YieldFlower =false;
boolean isUseful=true;  //value of isUseful changed to true
String[] Products1={"raw material","raw material","raw material"};   //values of arrays defined

}

class mustard extends Rabi {

boolean YieldFlower =false;
boolean isUseful=true;    //value of isUseful changed to true
String[] Products={"oil","oil","oil"};   //values of arrays defined

}

class maize extends Rabi {

boolean YieldFlower =false;
boolean Useful=true;  //value of isUseful changed to true
String[] Products1={"food","food","food"};  //values of arrays defined
}

public class CropTester {
public static void main(String[] args) {

Crop[] crops=new Crop[4];
crops[0]=new millets();
crops[1]=new cotton();
crops[2]=new mustard();
crops[3]=new maize();

for(Crop b:crops) {
b.eat();  //it prints false for isUseful , but it should print true
b.theyGrow();
b.UsefulProducts(b.Products1); //it results in an nullpointerexception error at runtime , but i have defined the values in the subclasses
b.FavourableSeason();
}
/*
millets mil=new millets();
//System.out.println(mil.isUseful);
mil.eat(mil.Useful);
mil.theyGrow();
mil.UsefulProducts(mil.Products1);
mil.FavourableSeason();
*/
}
}

1 个答案:

答案 0 :(得分:0)

你做错了。

在超类Crop中声明boolean isUsefull时,其默认值为false。 然后,当您使用声明的boolean isUsefull = true创建子类millets时,不要覆盖超类变量值,而是创建一个新值。如果要owerwrite超类变量的值,请使用构造函数

millets() { isUsefull=true;}

或使用init块

{isUsefull=true;}

在millets类中的任何方法体之外。