Java公共访问修饰符 [英] Java public access modifier
问题描述
我创建了一个类如下。
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 {
}
现在我想从AccessVaria访问Basics.java类中的变量.java类。
我试过这样做这个
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;
但我不能这样做并给我一个建议。 java总是请求getter()&即使变量具有公共访问修饰符,setter()方法也可以从不同的类访问变量?
我可以从C#中的另一个类访问一个类中的公共变量。净,但他们没有给出如此糟糕的经历。
所以,如果有人能解释如何解决这个问题?
谢谢!
Chiranthaka
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
推荐答案
在Java中,要访问给定类的任何属性,您必须创建首先是对象。
因此,如果要在类AccessVaria
Basics 的属性>,然后你必须在AccessVaria
里面创建一个类Basics
的实例。
For更多信息请点击此处。
.. java总是请求getter()& setter()方法来访问varia bles ..
Java建议您不要直接访问属性,使用getter / setter方法访问属性。这是一种编码惯例。
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 classBasics
inside classAccessVaria
, then you have to create a instance of classBasics
insideAccessVaria
.
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.
这篇关于Java公共访问修饰符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!