2014-04-02 1 views
0

저는 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(); 
*/ 
} 
} 

답변

0

잘못하고 있습니다.

슈퍼 클래스 자르기에서 부울 isUsefull을 선언하면 기본값은 false입니다. 그런 다음 boolean isUsefull = true로 선언 된 하위 클래스 millet을 만들 때 상위 클래스 변수 값을 덮어 쓰지 않으면 새 값을 만듭니다. 당신은 슈퍼 클래스 변수의 값을 owerwrite 하나를 사용 생성자

millets() { isUsefull=true;} 

또는 기장 클래스의 초기화 블록 어떤 방법 본체의

{isUsefull=true;} 

외부를 사용합니다.

관련 문제