-Prevents illegal values from entering fields ・ Create a "consistent class" ・ Directly connected to the object-oriented essence of "faithfully imitating the real world"
** Access modifier **
name | How to specify | Scope of permission for access |
---|---|---|
private | private | Only my own class |
package private | (Do not write anything) | Classes that belong to the same package as you |
protected | protected | Classes of children who belong to the same package as you or inherit from you |
public | public | All classes |
・ All fields are private
・ All methods are public
-Field manipulation via methods
getter -"Get" + "field name capitalized" -A method that simply calls the contents of the name field and returns it
Hero.java
public class Hero {
private String name;
public String getName() { //getName()Access the name field via
return this.name;
}
}
King.java
public class King {
void talk(Hero h) {
System.out.println("King: Welcome to our country, brave man" + h.getName() + "Yo.");
}
}
setter -"Set" + "Field name with capital letters at the beginning" -Methods that just assign values (in other classes)
Hero.java
public class Hero {
private String name;
public void setName(String name) {
this.name = name; //this.Never forget
}
}
name | How to specify | Scope of permission for access |
---|---|---|
package private | (Do not write anything) | Classes that belong to the same package as you |
public | public | All classes |
-The class name may be different from the source file name -Multiple classes may be declared in one source file
Hero.java
public class Hero {
}
class HeroSkill {
}
class HeroSinbol {
}
Hero.java
class Character {
}
class Boss {
}
Recommended Posts