Click here to Skip to main content
14,733,501 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have created a class as follows.

package basics;


 public class Basics {

   public int intMaths;
   public int intEnglish;
   public int intScience;

   }


Then I have created another class as the following and both classes are in the same package.

package basics;

 public class AccessVaria {



 }


Now I want to access the variable in the Basics.java class from the AccessVaria.java class.

I have tried to do that like this

intMaths = 80;


But I cannot do that and give me a suggestion. Do java always request for getter() & setter() methods to access variables from different classes even if the variables have the public access modifier ?

I have access public variables in one class from another class in C#.Net but they didn't give suchlike bad experience.

So if someone can explain how to solve this matter ?

Thank You!
Chiranthaka
Posted

1 solution

In Java, to access any properties of a given class, you have to create the object first.
Therefore if you want to access the properties of class Basics inside class AccessVaria , then you have to create a instance of class Basics inside AccessVaria.
For more information click here.

"..Do java always request for getter() & setter() methods to access variables.."

Java suggest you not to access the properties directly, use getter/setter method to access the properties. It is a coding convention.
   
Comments
CPallini 17-Jun-13 8:42am
   
I would say: "In Java, to access any, but static, properties of a given class, you have to create the object first"
-- Carlo the Nitpick
Shubhashish_Mandal 17-Jun-13 8:51am
   
yes I agree.
Chiranthaka Sampath 17-Jun-13 9:39am
   
Thanks for your comment !
Chiranthaka Sampath 17-Jun-13 13:34pm
   
I have created an object in the AccessVaria class but that object cannot be use like this

private Basics oBasics = new Basics();

oBasics.intMaths=10;

But when I used that object declared inside the main() it can be easily use.

Then what is the problem ?
sorawit amorn 20-Jun-13 15:46pm
   
you CAN initialize Basics object that way in AccessVaria. It would look like
public class AccessVaria{
private Basic bs = new Basic();

public void DoSomething(){
bs.intMaths = 10;
}
}

However, since bs object is private, you will not be able to use this instance in any other classes.

Please be sure to read the coding convention, this will help you a lot later on
Shubhashish_Mandal 18-Jun-13 2:59am
   
post your code. did you create and set the instance value inside any method ?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900