[英]How to access instance variables and methods in Java
这是一个用于访问实例变量和方法的 Java 程序(系统在全局声明“int puppyAge;”中预期的标记“int”导入上抛出语法错误:-
是否可以选择全局声明变量:
package instancevariableandmethods;
int puppyAge;
public class Instancevariable {
public Instancevariable(String name) {
System.out.println("The name is:" + name);
}
public void setAge(int age) {
puppyAge = age;
}
public int getAge() {
System.out.println("Puppy's age is: " + puppyAge);
return puppyAge;
}
public static void main(String[] args) {
Instancevariable myPuppy = new Instancevariable("tommy");
/* Call class method to set puppy's age */
myPuppy.setAge(2);
/* Call another class method to get puppy's age */
myPuppy.getAge();
/* You can access instance variable as follows as well */
System.out.println("Variable Value:" + myPuppy.puppyAge );
}
}
像下面这样声明你的变量:
public class Instancevariable
{
int puppyAge;
//// The rest of your code
}
示例 - 全局和局部变量声明
public class Car {
private int speed; // Private variable declaration
public int wheels; // Public variable declaration
/* ...constructor, etc... */
public void speedUp() {
// Local variable declaration, in line assignment,
// only seen within the speedUp method
int speedIncrease = 10;
speed += speedIncrease;
}
}
Java 中没有这样的全局变量。 类级别有静态变量,但它们在类的所有实例之间共享。
在这种情况下,您需要一个类字段:
package instancevariableandmethods;
public class Instancevariable
{
int puppyAge;
public Instancevariable(String name) {
System.out.println("The name is: " + name);
}
public void setAge(int age) {
puppyAge = age;
}
public int getAge() {
System.out.println("Puppy's age is: " + puppyAge);
return puppyAge;
}
public static void main(String[] args) {
Instancevariable myPuppy = new Instancevariable("tommy");
/* Call the class method to set the puppy's age */
myPuppy.setAge(2);
/* Call another class method to get the puppy's age */
myPuppy.getAge();
/* You can access instance variable as follows as well */
System.out.println("Variable Value: " + myPuppy.puppyAge);
}
}
你的int puppyAge;
属于类,不属于类:
public class Instancevariable {
int puppyAge;
// The rest of your code
}
你做错了。 你可以在你的类中声明一个类变量。 如果你想让它超级全球化,请使用“public”。
public class TemplateVO
{
public int puppyAge;
// The rest of your code
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.