构造函数与getter和setter之间的区别

我一直在做大学项目的作业。有一次,当您实际上可以使用构造函数方法来实现相同的结果时,我对于getter和setter的实际使用感到困惑。我已经搜索并找到许多答案,但没有令人满意的解释。我有如下laptop.java

public class laptop {

private String model;

public laptop(String brand){

model=brand;

}

public String toString(){

return "Laptop Brand is: "+ model;

}

}

和laoptopRecords.java调用构造函数为

public class laptopRecords {

public static void main(String[] args) {

// TODO Auto-generated method stub

laptop laptop1=new laptop("Dell");

System.out.println(laptop1);

}

}

在这里,我没有使用getter和setter方法,并且为每个便携式计算机对象都获得了理想的结果。

如果我以如下方式在laptopRecord.java中使用getter和setter方法进行另一种方式处理,则会得到相同的结果。但是,如果实际上我们也可以通过构造函数获得结果,那么我就没有得到getter和setter方法的用途。

具有getter和setter的laptop.java

public class laptop {

private String model;

public laptop(String brand){

model=brand;

}

public void setlaptop(String brand){

model=brand;

}

public String getlaptop(){

return model;

}

public String toString(){

return "Laptop Brand is: "+ model;

}

}

回答:

  • 实际上在POJO / Bean类中可用的getters()和setters。
  • 在Java类中使用getters(),setters()的主要原因是
  • 在POJO / Bean类中,我们将所有属性声明为 这意味着这些类属性不能在其他类和包中使用,因此,我们可以实现封装。

  • 我认为您知道构造函数的定义,
  • 我们可以说另一种方式,即

以上是 构造函数与getter和setter之间的区别 的全部内容, 来源链接: utcz.com/qa/404150.html

回到顶部