java is setter,Java:Setter Getter和constructor

本文探讨了Java中构造器和getter/setter的用途。构造器用于初始化对象,而getter/setter提供数据访问的安全性和灵活性。尽管默认构造器通常存在,但在特定条件下,如当对象必须在创建时提供所有必要属性时,参数化构造器是必需的。例如,在Book类中,没有无参构造器,因为每本书都需要标题和作者。因此,参数化构造器确保了对象正确初始化并符合业务规则。
摘要由CSDN通过智能技术生成

I'm a bit confused about the use of getter/setters and constructors (see the below code for an example)

public class ExampleClass {

private int value = 0;

public ExampleClass () {

value = 0;

}

public exampleClass (int i) {

this.value=i;

}

public int getValue() {

return value;

}

public void setValue(int val) {

this.value=val;

}

public static void main(String[] args) {

ExampleClass example = new ExampleClass (20);

example.setValue(20);

//Both lines above do same thing - why use constructor?

System.out.println(example.getvalue());

}

}

All I've learned is that we need getters/setters for security and that they can also be used to change or edit values later on.

My question is that if the constructor is the point of initialization and a default constructor is always present, why use a constructor with parameters to initialize values instead of getters/setters?. Wouldn't using the getter and setter provide security as well being able to easily change values at any stage. Please clarify this point for me.

解决方案

default constructor is always there

Well actually its not always there. A default constructor is the one which is provided by the compiler (of course it is a no-arg constructor ) Only if there is no other constructor defined in the class

why we use constructor with parameters to initialize values instead of set get

Because there could be a condition that an object can always be created only when all the values are provided at the time of initialization itself and there is no default value. So all values must be provided otherwise code will not compile.

Consider this Book class

public class Book {

private String title;

private String author;

public Book(String title, String author){

this.title = title;

this.author = author;

}

//getters and setters here

}

Consider a condition where a book can be created only if it has title and author.

You cannot do new Book() because no-arg constructor is absent and compiler will not provide one because one constructor is already defined.

Also you cannot do new Book() because our condition does not meet as every book requires a title and author.

This is the condition where parameterized constructor is useful.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值