Java类和访问器方法 [英] Class and accessor methods Java
问题描述
我不理解访问器方法,并且无法创建setAge,getAge和getName.
I don't understand accessor methods and I'm stuck with creating setAge, getAge and getName.
这是问题:
添加三个访问器方法setAge
,getAge
和getName
.这些方法应设置并获取相应实例变量的值.
Add three accessor methods, setAge
, getAge
and getName
. These methods should set and get the values of the corresponding instance variables.
public class Player {
protected int age;
protected String name;
public Player(String namArg) {
namArg = name;
age = 15;
}
}
推荐答案
访问器方法用于返回私有或受保护字段的值.它遵循一种命名方案,在方法名称的开头加上单词"get".例如,让我们为名称添加访问器方法:
An accessor method is used to return the value of a private or protected field. It follows a naming scheme prefixing the word "get" to the start of the method name. For example let's add accessor methods for name:
class Player{
protected name
//Accessor for name
public String getName()
{
return this.name;
}
}
您可以通过以下对象访问受保护名称的值:
you can access the value of protected name through the object such as:
Player ball = new Player()
System.out.println(ball.getName())
mutator方法用于设置私有字段的值.它遵循一种命名方案,在方法名称的开头加上单词"set".例如,让我们为名称添加mutator字段:
A mutator method is used to set a value of a private field. It follows a naming scheme prefixing the word "set" to the start of the method name. For example, let's add mutator fields for name:
//Mutator for name
public void setName(String name)
{
this.name= name;
}
现在我们可以使用以下方法设置玩家名称: ball.setName('David');
now we can set the players name using: ball.setName('David');
这篇关于Java类和访问器方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!