我是靠谱客的博主 顺心砖头,最近开发中收集的这篇文章主要介绍java is setter,Java:Setter Getter和constructor,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

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.

最后

以上就是顺心砖头为你收集整理的java is setter,Java:Setter Getter和constructor的全部内容,希望文章能够帮你解决java is setter,Java:Setter Getter和constructor所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(43)

评论列表共有 0 条评论

立即
投稿
返回
顶部