【问题标题】:How to get access the method from other method of class?如何从类的其他方法访问该方法?
【发布时间】:2017-10-29 15:32:49
【问题描述】:

我想计算盒子的密度(体积)。我计算了盒子的体积,但我无法计算盒子的密度。

import java.util.*;
     class DimBox{
        int width;
        int depth;
        int height;
        int s;
            DimBox(int width,int depth,int height){
            this.width=width;
            this.height=height;
            this.depth=depth;
        }
            int getDimBox(){
            int s= width*depth*height;
            return s;
        }
     }
     class DensityBox{
        int density;
        int getDimBox;
        int getWeightBox();
            int getDensity(int density){
            density = getDimBox * getWeightBox();
            return density;
        }
     }
     class WeightBox{
        int weight;
            WeightBox(int weight){
            this.weight=weight;
        }
        int getWeightBox(){
            return weight;
        }
         }
     public class Main {
        public static void main(String[] args)  {
        DimBox dimBox=new DimBox(20,50,30);
        System.out.println(dimBox.getDimBox());
        WeightBox weightBox=new WeightBox(75);
        DensityBox densityBox=new DensityBox();
        System.out.println(densityBox.density);
        }
     }

【问题讨论】:

  • 请输入您的代码并展示您到目前为止所做的工作。
  • 你的代码在哪里?
  • 我的代码在顶部
  • 这段代码还能编译吗? int getWeightBox(); 没有方法体,这也不是抽象类。糟糕的代码也是如此。零面向对象。如果你想调用一个方法,像这样System.out.println(densityBox.getDensity()); 并确保 getter 没有输入参数,因为这种情况的 getter 没有这样的参数是没有意义的
  • 谢谢,但我知道。只是忘了写()。

标签: java class methods


【解决方案1】:

我假设你想要类似的东西:

class DensityBox{

    float weight, volume;

    DensityBox(float weight, float volume){
        this.weight = weight; // check >0
        this.volume = volume; //check >=0
    }

    float getDensity() {  return volume/weight;   }
 }

并使用它:

DensityBox densityBox = new DensityBox(weightBox.getWeightBox(), dimBox.getDimBox());
float density = densityBox.getDensity();

【讨论】:

  • 非常感谢
【解决方案2】:

注意我没有给出直接代码,因为给出直接代码不会帮助您理解基础知识,并且以后会遇到很多困难。

这可以通过多种不同的方式解决。

一个选项是 Composition,DensityBox 应该有 DimBox 实例和 Weight 实例变量来访问它们的方法。

无论是在构造 DensityBox 实例期间还是稍后在 DensityBox 实例上使用 setter 时,都在 DensityBox 实例中设置 DimBox 和 Weight 实例,以便可以访问它们的成员方法。

另一种选择是使用具有不同类的对象作为参数的静态辅助方法来完成繁琐的工作。

另一种选择是调用 main 方法中所有类的方法,以在 main 方法本身中进行所需的计算。但我不推荐这个,因为它没有演示 OOP,这只是 FYI。

您需要回归基础以了解基本的 OOP 概念并了解对象的组合或如何使用将对象传递给它的静态辅助方法来完成脏活。

【讨论】:

  • 非常感谢 JRG。最佳答案!我想在你的答案上打勾,但我不能。
  • 因为您已经选择了另一个答案 :),如果您喜欢它,请投票!
  • @Iwantask 我为你做了(0:
猜你喜欢
  • 2010-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-18
  • 2014-09-05
相关资源
最近更新 更多