如何在Java中对非静态方法进行静态引用?

时间:2016-04-04 06:46:14

标签: java class methods static

对于赋值,我必须创建一个接受分数的类,但每当我尝试引用程序中的方法时,我都会收到此错误:“无法对非静态方法进行静态引用”。这是我的计划的一部分:

public class Fraction {

  public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    String operator;

    System.out.println("What is your numerator?");
    long num = keyboard.nextInt();
    System.out.println("What is your denominator?");
    long denom = keyboard.nextInt();
    System.out.println("Your current fraction is: " + toString());

    keyboard.close(); }

  private long numerator;
  private long denominator;

  public Fraction() {  //constructs fraction 0/1
    numerator = 0;
    denominator = 1; }

  public Fraction(long num){  //constructs fraction n/1
    numerator = num;
    denominator = 1; }

  public Fraction(long num, long denom){  //constructs fraction n/d 
    numerator = num;
    if (denom == 0){  //make sure denom isn't 0
      throw new ArithmeticException(); }
    else{
      denominator = denom; }
    setSign(); } 

  public void add(Fraction fraction){  //addition
    if(fraction.denominator == this.denominator){
     this.numerator += fraction.numerator; }
    else{
      this.numerator *= fraction.denominator;
      this.denominator *= fraction.denominator;
      long temp = fraction.numerator * this.denominator;
      this.numerator += temp; } }   

  public String toString(){  //returns fraction as string
    return (numerator + "/" + denominator); }

  }

如何从main方法访问这些方法?另外,我如何调用像添加方法这样的方法(代码看起来像什么)?

非常感谢任何帮助,谢谢!

2 个答案:

答案 0 :(得分:0)

非静态方法意味着它是类的方法。换句话说,您需要声明一个新的分数来调用这些方法。例如:

Fraction frac = new Fraction(2);
Fraction toAdd = new Fraction(3);
frac.add(toAdd);

注意如何使用分数的实例调用add方法,在本例中为frac(frac.add)。

可以使用Fraction.add调用静态方法,但是非静态方法要求您首先创建类的实例(使用新的Fraction())。

答案 1 :(得分:0)

您在没有实际实例的情况下调用toString()实例方法。您应该首先创建类Fraction的对象,然后为该对象调用toString()方法。