前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >java mutator,Java – 使用Accessor和Mutator方法「建议收藏」

java mutator,Java – 使用Accessor和Mutator方法「建议收藏」

作者头像
全栈程序员站长
发布2022-11-04 15:27:00
发布2022-11-04 15:27:00
3210
举报

大家好,又见面了,我是你们的朋友全栈君。

I am working on a homework assignment. I am confused on how it should be done.

The question is:

Create a class called IDCard that contains a person’s name, ID number,

and the name of a file containing the person’s photogrpah. Write

accessor and mutator methods for each of these fields. Add the

following two overloaded constructors to the class:

public IDCard() public IDCard(String n, int ID, String filename)

Test your program by creating different ojbects using these two

constructors and printing out their values on the console using the

accessor and mutator methods.

I have re-written this so far:

public class IDCard {

String Name, FileName;

int ID;

public static void main(String[] args) {

}

public IDCard()

{

this.Name = getName();

this.FileName = getFileName();

this.ID = getID();

}

public IDCard(String n, int ID, String filename)

{

}

public String getName()

{

return “Jack Smith”;

}

public String getFileName()

{

return “Jack.jpg”;

}

public int getID()

{

return 555;

}

}

解决方案

Let’s go over the basics:

“Accessor” and “Mutator” are just fancy names fot a getter and a setter.

A getter, “Accessor”, returns a class’s variable or its value. A setter, “Mutator”, sets a class variable pointer or its value.

So first you need to set up a class with some variables to get/set:

public class IDCard

{

private String mName;

private String mFileName;

private int mID;

}

But oh no! If you instantiate this class the default values for these variables will be meaningless.

B.T.W. “instantiate” is a fancy word for doing:

IDCard test = new IDCard();

So – let’s set up a default constructor, this is the method being called when you “instantiate” a class.

public IDCard()

{

mName = “”;

mFileName = “”;

mID = -1;

}

But what if we do know the values we wanna give our variables? So let’s make another constructor, one that takes parameters:

public IDCard(String name, int ID, String filename)

{

mName = name;

mID = ID;

mFileName = filename;

}

Wow – this is nice. But stupid. Because we have no way of accessing (=reading) the values of our variables. So let’s add a getter, and while we’re at it, add a setter as well:

public String getName()

{

return mName;

}

public void setName( String name )

{

mName = name;

}

Nice. Now we can access mName. Add the rest of the accessors and mutators and you’re now a certified Java newbie.

Good luck.

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年9月13日 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档