954,153 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Accessing variables of another class

Hey all. I would like to find out how i can access/ get the value of a variable in a different class. this is part of the code which shows what I was trying to do.

public class A{

	protected int x;
	
          //missing code
	C obj = new C (); 
	C.x=x; //i get an error "indentifier expected"
}

class C extends B{
protected int x;
	public int getInt()
	{
		System.out.print("Enter Value ");
		x=scan.nextInt();
	        return x;
	}
}
joshmo
Posting Whiz in Training
280 posts since Oct 2007
Reputation Points: 19
Solved Threads: 20
 

Hello,
You need to change your class A, because you have two problems:
1st - you don't have method at class A. you need to put your code inside one method
2nd - you can't access a instance variable like a class variable (static)

this code should work:

public class A{

protected int x;
-> public void test(){
C obj1 = new C ();
-> obj1.x = x;
}

I hope that helps you.

ablago
Newbie Poster
11 posts since Sep 2008
Reputation Points: 10
Solved Threads: 1
 

yep. that helped.. thanks

joshmo
Posting Whiz in Training
280 posts since Oct 2007
Reputation Points: 19
Solved Threads: 20
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You