【问题标题】:why does a void method without void in the head of the method definition not cause error? [duplicate]为什么方法定义头部没有 void 的 void 方法不会导致错误? [复制]
【发布时间】:2014-11-24 00:18:56
【问题描述】:

方法定义LibraryBook 是一个void 方法,但它的定义头部没有void。为什么它不会导致错误?我尝试了另一种方法定义,而另一种确实导致了错误:invalid method declaration

/**
/The following is a definition of the LibraryBook class.
/This class has four instance variables and one static (or class) variable.
/One of the instance variables is a type Author.
**/
public class LibraryBook
{
    private int bookId;
    private String bookName;
    private Author bookAuthor;
    private double bookPrice;
    private static double totalInvValue;


    public LibraryBook (int id, String name, Author author, double price)
    {
        bookId = id;
        bookName = name;
        bookAuthor = author;
        bookPrice = price;
        totalInvValue += price;
    }


    public String toString()
    {
        String response = "";
        response += "Book Name is: " + bookName;
        response += "\nIt costs: " + bookPrice;
        response += "\nIt was " + bookAuthor.toString();
        return response;
    }


    public static double getTotValue()
    {
        return totalInvValue;
    }

}

【问题讨论】:

  • 因为LibraryBook() 是一个构造函数,构造函数不返回任何内容,甚至不返回void。它不同于 普通 方法。

标签: java methods


【解决方案1】:

构造函数不是它们不返回任何东西的方法

【讨论】:

    【解决方案2】:

    您知道它是一个构造函数,因为它与类本身具有完全相同的名称。

    类名 = 构造函数的名称

    它不是一种方法,因为它不是一个。

    在实例化对象时使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-03
      • 2020-04-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多