Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
InheritanceApp.java:37:错误:非静态变量无法从静态上下文引用此变量_Java - Fatal编程技术网

InheritanceApp.java:37:错误:非静态变量无法从静态上下文引用此变量

InheritanceApp.java:37:错误:非静态变量无法从静态上下文引用此变量,java,Java,我在以下代码中遇到错误: public class InheritanceApp { class Product { // atributes int p_id; String name; double price; // constructor Product() { System.out.println(">> Product Object Con

我在以下代码中遇到错误:

public class InheritanceApp {

    class Product {

        // atributes
        int p_id;
        String name;
        double price;

        // constructor
        Product() {
            System.out.println(">> Product Object Constructed");
        }

        // method
        public void setProductDetails(int p_id, String name, double price) {

            this.p_id = p_id;
            this.name = name;
            this.price = price;
        }

        // Read data from product object
        public void showProductDeatails() {
            System.out.println("---------Product Id: " + p_id + "-----------");
            System.out.println("Name : \t" + name);
            System.out.println("Price : \t" + price);
            System.out.println("------------------------------------------------");
        }

    }

    public static void main(String[] args) {

        // Creat object : product
        Product product = new Product();

        // Writting data into an object
        product.setProductDetails(100, "Nike", 6700.60);

        // Reading data from an object
        product.showProductDeatails();

    }

}
错误显示:

InheritanceApp.java:37:错误:非静态变量无法从静态上下文引用此变量 产品=新产品()


Java嵌套类分为两种类型:静态嵌套类和非静态嵌套类(也称为“内部”)。静态嵌套类与任何其他顶级类相同,仅为便于打包而嵌套,而内部类与特定实例关联

使用静态嵌套类:

OuterClass.StaticClass obj = new OuterClass.StaticClass();
使用内部类:

OuterClass outObj = new OuterClass();
OuterClass.InnerClass inObj = outerObject.new InnerClass();
现在,根据您的用例,使用您需要的任何方法。例如:

InheritanceApp inheritanceApp = new InheritanceApp();
InheritanceApp.Product product = InheritanceApp.new Product();

在中找到更多信息。

类产品
声明为
静态类产品
(最简单),或使用
Product=new InheritanceApp().new Product()初始化变量