Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

basic constructor question

Status
Not open for further replies.

786snow

Programmer
Nov 12, 2006
75
Hi, what am i doing wrong here. I have couple of variable in the constructor but when try
to print them i get errors



Code:
public class HelloWorldApp2 {

 HelloWorldApp2 (String var1, int var2){

String instanceVariable1 = var1;
int instanceVariable2 =var2;

}

 public static void main(String args[]) {
 HelloWorldApp2 object6 = new HelloWorldApp2("USA", 2);
 object6.letSee();
}

public void letSee()
	{

		System.out.println("calling class no 4\n");
		System.out.println(instanceVariable1 + "\n");
		System.out.println(instanceVariable2 + "\n");
	
	}


}

I get these erors
Code:
 C:\Program Files\Java\jdk1.5.0_06\bin>javac HelloWorldApp2.java
HelloWorldApp2.java:20: cannot find symbol
symbol  : variable instanceVariable1
location: class HelloWorldApp2
                System.out.println(instanceVariable1 + "\n");
                                   ^
HelloWorldApp2.java:21: cannot find symbol
symbol  : variable instanceVariable2
location: class HelloWorldApp2
                System.out.println(instanceVariable2 + "\n");
                                   ^
2 errors

 
instanceVariable1 and 2 are not in letsee() method's scope; that is, it has no idea they exist. You have them declared and initialized inside the constructor, which only the constructor can use; pretty much useless.

Declare them in the main body of the class, then other methods can use them.

Code:
public class HelloWorldApp2 {

[red]
 private String instanceVariable1;
 private int instanceVariable2;
[/red]

 HelloWorldApp2 (String var1, int var2){
[red]
     instanceVariable1 = var1;
     instanceVariable2 =var2;
[/red]
}

 public static void main(String args[]) {
 HelloWorldApp2 object6 = new HelloWorldApp2("USA", 2);
 object6.letSee();
}

public void letSee()
    {

        System.out.println("calling class no 4\n");
        System.out.println(instanceVariable1 + "\n");
        System.out.println(instanceVariable2 + "\n");
    
    }


}



Hope that helps,
Ron

typedef map<GiantX,gold, less<std::shortestpathtogold> > AwesomeMap;
 
thanks a lot for your help ........ I understand now
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top