当前位置: 代码迷 >> java >> Java中的驱动程序类/类的范围存在问题
  详细解决方案

Java中的驱动程序类/类的范围存在问题

热度:91   发布时间:2023-07-16 17:31:03.0

我制作了一个Sphere类,其中包含一些功能。 然后,我制作了一个MultiSphere类,它充当“驱动程序类”。 我将Sphere类放在驱动程序类中(这是您应该如何使用类/驱动程序类吗?),现在看来我在尝试访问Sphere.diameter变量时遇到错误,因为它正在通过Multisphere全班第一

我的IDE说

Multisphere.this cannot be referenced from a static context

我得到错误

non-static variable this cannot be referenced from a static context

当我尝试在最后一行创建Sphere类的新实例时:

Sphere circle = new Sphere(15);

完整的代码:

import java.util.Scanner;
import java.lang.Math;

public class MultiSphere {

    public class Sphere {
        // Instance Variables
        double diameter;

        // Constructor Declaration of Class
        private Sphere(double diameter) {
            this.diameter = diameter;
        }

        private double getDiameter() {
            System.out.printf("Diameter is %f \n", diameter);
            return diameter;
        }

        // Allows user to modify the diameter variable
        private double setDiameter() {
            System.out.print("Enter the diameter for the sphere: \n");
            this.diameter = new Scanner(System.in).nextDouble();
            return diameter;

        }

        private void Volume() {
            double radius = diameter / 2;
            double volume = (4 * Math.PI * Math.pow(radius, 3)) / 3;
            System.out.printf("The volume of the sphere is: %f \n", volume);

        }

        private void surfaceArea() {
            double radius = diameter / 2;
            double surfaceArea = 4 * Math.PI * Math.pow(radius, 2);
            System.out.printf("The surface area is: %f \n", surfaceArea);

        }

    }

    public static void main(String[] args) {
        System.out.printf("Hello World");
         Sphere circle = new Sphere(15);
    }
}

这里的问题是Sphere是一个非静态内部类。 这意味着您需要一个MultiSphere实例才能访问它:

MultiSphere ms = new MultiSphere();
Sphere s = new ms.Sphere();

另外,您可以仅使Sphere类为静态:

public static class Sphere {

最后,您可以将这些类放入分别名为MultiSphere.javaSphere.java两个文件中。 就个人而言,我更喜欢这一点。

您必须将私有范围更改为公共范围。

    private Sphere(double diameter) {
        this.diameter = diameter;
    }

像那样

    public Sphere(double diameter) {
        this.diameter = diameter;
    }

除非您在同一类中调用私有构造函数,否则没有意义。

  相关解决方案