インポートって、要するに違うファイルからの読み込みね。すっかり忘れてる or スルーしてた。
package jp.hpscript.myapp;
import jp.hpscript.myapp.model.User;
import jp.hpscript.myapp.model.AdminUser;
public class MyApp {
public static void main(String[] args){
User tom = new User("Tom");
// System.out.println(tom.name);
tom.sayHi();
AdminUser bob = new AdminUser("bob");
// System.out.println(bob.name);
bob.sayHi();
bob.sayHello();
}
}
package jp.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);
}
}
package jp.hpscript.myapp.model;
public class AdminUser extends User {
public AdminUser(String name){
super(name);
}
public void sayHello(){
System.out.println("hello!" + this.name);
}
@Override public void sayHi(){
System.out.println("[admin]hi!" + this.name);
}
}
[vagrant@localhost java]$ javac jp/hpscript/myapp/MyApp.java
[vagrant@localhost java]$ java jp.hpscript.myapp.MyApp
hi!Tom
[admin]hi!bob
hello!bob
setter, getter
class User {
private String name;
private int score;
public User(String name, int score){
this.name = name;
this.score = score;
}
public int getScore(){
return this.score;
}
public void setScore(int score){
if(score > 0){
this.score = score;
}
}
}
public class MyApp {
public static void main(String[] args){
User tom = new User("Tom", 65);
tom.setScore(85);
tom.setScore(-22);
System.out.println(tom.getScore());
}
}
// static
class User {
private String name;
private static int count = 0;
public User(String name){
this.name = name;
User.count++;
}
public static void getInfo(){
System.out.println("# of instances: " + User.count);
}
}
public class MyApp {
public static void main(String[] args){
User.getInfo();
User tom = new User("Tom");
User.getInfo();
User john = new User("John");
User.getInfo();
}
}