如何在Java中访问实例变量和方法

如何在Java中访问实例变量和方法,java,Java,这是一个用于访问实例变量和方法的Java程序(系统在全局声明“int puppyAge;”中预期的标记“int”导入上抛出语法错误:- 是否有全局声明变量的选项: package instancevariableandmethods; int puppyAge; public class Instancevariable { public Instancevariable(String name) { System.out.println("The name

这是一个用于访问实例变量和方法的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 );
    }
}

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);
    }
}
如下所示声明变量:

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;
    }
}

您的
int-puppyAge;
属于该类,而不是上面的:

public class Instancevariable {
    int puppyAge;
    // The rest of your code
}

你做错了。你可以在你的类中声明一个类变量。如果你想使它超全局,请使用“public”


取决于“全局”的含义。Java没有全局变量,一切都在一个类中
public class TemplateVO
{
    public int puppyAge;
    // The rest of your code