943,852 Members | Top Members by Rank

Ad:
  • Java Discussion Thread
  • Marked Solved
  • Views: 3128
  • Java RSS
Oct 27th, 2008
0

Accessing variables of another class

Expand Post »
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.
Java Syntax (Toggle Plain Text)
  1. public class A{
  2.  
  3. protected int x;
  4.  
  5. //missing code
  6. C obj = new C ();
  7. C.x=x; //i get an error "indentifier expected"
  8. }
  9.  
  10. class C extends B{
  11. protected int x;
  12. public int getInt()
  13. {
  14. System.out.print("Enter Value ");
  15. x=scan.nextInt();
  16. return x;
  17. }
  18. }
Similar Threads
Reputation Points: 19
Solved Threads: 20
Posting Whiz in Training
joshmo is offline Offline
280 posts
since Oct 2007
Oct 27th, 2008
0

Re: Accessing variables of another class

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.
Reputation Points: 10
Solved Threads: 1
Newbie Poster
ablago is offline Offline
11 posts
since Sep 2008
Oct 27th, 2008
0

Re: Accessing variables of another class

yep. that helped.. thanks
Reputation Points: 19
Solved Threads: 20
Posting Whiz in Training
joshmo is offline Offline
280 posts
since Oct 2007

This thread is solved

Either the thread starter or a moderator has marked this thread as solved. You can most likely trust the responses and answers given. There is most likely no reason for any further responses to be posted here. If you have a related question, please start a new thread in this forum instead.

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in Java Forum Timeline: StringUtil Help(AP CS Work Urgent help please!)
Next Thread in Java Forum Timeline: <identifier> expected? Pls help my code!





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC