インポートって、要するに違うファイルからの読み込みね。すっかり忘れてる or スルーしてた。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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(); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | 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()); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | // 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(); } } |