用于访问实例变量和方法的java程序(系统在全局声明中强制使用令牌“int”导入时出现语法错误“int puppyAge;”: -
是否可以选择全局声明变量: -
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 );
}
}
答案 0 :(得分:2)
声明您的variable
,如下所示
public class Instancevariable
{
int puppyAge;
//// 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 speedUp method
int speedIncrease = 10;
speed += speedIncrease;
}
}
答案 1 :(得分:1)
请格式化您的代码段并使用java编码约定。
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 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);
}
}
答案 2 :(得分:1)
您的NAN
属于班级,不属于上课。
int puppyAge;
答案 3 :(得分:1)
你做错了。您可以在类中声明类变量。如果你想让它超级全球化使用" public"。
public class TemplateVO
{
public int puppyAge;
//rest of your code