[Java] java (encapsulation)

1 minute read

Encapsulation

・Preventing illegal values in the field ・Create a “class that does not conflict” ・It is directly connected to the object-oriented essence of “faithfully copying the real world.”

Restrict access to fields and methods

Access qualifier

Name How to specify Range to allow access  
private   private own class only
package private (do not write anything) Class belonging to the same package as me  
protected protected Child classes that belong to the same package as me or inherit from me  
public public all classes  

Standard access modifiers for members

・All fields are private ・All methods are public

getter and setter

・Field operations via methods

getter

・”Get” + “capitalization of the field name” ・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() {// access the name field via getName()
    return this.name;
  }
}

King.java


public class King {
  void talk(Hero h) {
    System.out.println("King: Welcome to our country, brave man" + h.getName() + "yes.");
  }
}

setter

  • “Set” + “capitalization of the field name” Method that only assigns a value (in another class)

Hero.java


public class Hero {
  private String name;

  public void setName(String name) {
    this.name = name; // never forget this.
  }
}

Access control for classes

Name How to specify Range to allow access
package private (do not write anything) class that belongs to the same package as me
public public all classes

Features of non-public (package private) class

  • The class name may differ 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 {
}