在Java中检查Getter和Setter的可用性

时间:2019-06-25 02:06:47

标签: java

我有一个Book类,带有私有变量bookName(type:String),bookPrice(type:int),authorName(type:String)。我为这些私有变量包括了适当的getter和setter方法。

创建了另一个具有主要方法的TestBook类。我需要从用户那里获取详细信息bookName,bookPrice,authorName。

在Testbook类中创建的书籍类的对象,并使用设置器为其属性分配值。也可以使用getters方法打印输出输出。

我编写了整个代码,但失败了。

失败1:检查bookName属性的getter / setter的可用性 Fail2:检查bookPrice属性的getter / setter的可用性 失败3:检查authorName属性的getter / setter的可用性

Book.java

 public class  Book {

         private String bookName;
         private int bookPrice;
         private String authorName;

         //getters

         public String getbookName(){
             return bookName;
         }

        public String getauthorName(){
              return authorName;
        }
        public int getbookPrice(){
            return bookPrice;
        }

       //setters


        public void setbookName(String newName){
             this.bookName = newName;
        }
        public void setbookPrice(int bokPrice){
            this.bookPrice = bokPrice;
        }
        public void setauthorName(String author){
            this.authorName = author;
        }


    }

TestBook.java

 import java.util.Scanner;

     class TestBook {

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

         String name1,name2;
         int num;

        // Getting user input

        System.out.println("Enter the Book name:");
        name1 = my.nextLine();

        System.out.println("Enter the price:");
        num = my.nextInt();

        String re = my.nextLine();

        System.out.println("Enter the Author name:");
        name2 = my.nextLine();

        //Setting values of private variable using setters

        Book myObj = new Book();
        myObj.setbookName(name1);
        myObj.setbookPrice(num);
        myObj.setauthorName(name2);

        //Printing values using getters

        System.out.println("Book Details");
        System.out.println("Book Name :"+myObj.getbookName());
        System.out.println("Book Price :"+myObj.getbookPrice());
        System.out.println("Author Name :"+myObj.getauthorName());



        }
    }

1 个答案:

答案 0 :(得分:2)

getbookName()应该是getBookName()。对于您的getter和setter的全部setbookName()应该为setBookName(),依此类推。那是正确的Java约定。而且我只能假设测试人员正在寻找的标准。