Java packageの書き方

クラス

class User {
  String name = "Me"; // field

  void sayHi(){
    System.out.println("hi!");
  }
}

public class MyApp{

  public static void main(String[] args){

    User tom;
    tom = new User(); // instance
    System.out.println(tom.name);
    tom.sayHi();
  }
}

コンストラクター:クラスの初期化

class User {
  String name;

  // constructor
  User(String name){
    this.name = name;
  }

  // User(){
  //   this.name = "me";
  // }

  User(){
    this("me!");
  }

  void sayHi(){
    System.out.println("hi!" + this.name);
  }
}

public class MyApp{

  public static void main(String[] args){

    User tom;
    tom = new User(); // instance
    System.out.println(tom.name);
    tom.sayHi();
  }
}

クラスの継承とoverride

class User {
  String name;

  User(String name){
    this.name = name;
  }

  void sayHi(){
    System.out.println("hi!" + this.name);
  }
}

class AdminUser extends User {
  AdminUser(String name){
    super(name);
  }
  void sayHello(){
    System.out.println("hello!" + this.name);
  }

  // override
  @Override
  void sayHi(){
    System.out.println("[admin] hi!" + this.name);
  }

}

public class MyApp{
  public static void main(String[] args){

    User tom = new User("tom"); // instance
    System.out.println(tom.name);
    tom.sayHi();

    AdminUser bob = new AdminUser("bob"); // instance
    System.out.println(bob.name);
    bob.sayHi();
    bob.sayHello();
  }
}

public:アクセス可
private:同じクラスならアクセス可能
protected:同じパッケージのみ

パッケージ化
com/hpscript/myapp/MyApp.java

package com.hpscript.myapp;
import com.hpscript.myapp.model.User;
import com.hpscript.myapp.model.AdminUser;
// import hpscript.myapp.model.*;

public class MyApp{
  public static void main(String[] args){

    User tom = new User("tom"); // instance
    // System.out.println(tom.name);
    tom.sayHi();

    AdminUser bob = new AdminUser("bob"); // instance
    // System.out.println(bob.name);
    bob.sayHi();
    bob.sayHello();
  }
}

com/hpscript/myapp/model/User.java

package com.hpscript.myapp.model;

public class User {
  protected String name;

  public User(String name){
    this.name = name;
  }

  public void sayHi(){
    System.out.println("hi!" + this.name);
  }
}

com/hpscript/myapp/model/AdminUser.java

package com.hpscript.myapp.model;

public class AdminUser extends User {
  public AdminUser(String name){
    super(name);
  }
  public void sayHello(){
    System.out.println("hello!" + this.name);
  }

  // override
  @Override
  public void sayHi(){
    System.out.println("[admin] hi!" + this.name);
  }

}