public static void sayHi(){ System.out.println("Hi!"); } public static void main(String[] args){ sayHi(); }
public static void sayHi(String name){ System.out.println("Hi!" + name); } public static void main(String[] args){ sayHi("Tom"); sayHi("Bob"); }
[vagrant@localhost java]$ javac MyApp.java
[vagrant@localhost java]$ java MyApp
Hi!Tom
Hi!Bob
public static String sayHi(String name){ return "Hi!" + name; } public static void main(String[] args){ String msg = sayHi("Steve"); System.out.println(msg); }
[vagrant@localhost java]$ javac MyApp.java
[vagrant@localhost java]$ java MyApp
Hi!Steve
classを使ってみよう
class User { String name = "Me!"; void sayHi(){ System.out.println("hi!"); } } public class MyApp { public static void main(String[] args){ User tom; tom = new User(); System.out.println(tom.name); tom.sayHi(); } }
[vagrant@localhost java]$ javac MyApp.java
[vagrant@localhost java]$ java MyApp
Me!
hi!
なるほど。
コンストラクタ
class User { String name; User(String name){ this.name = name; } void sayHi(){ System.out.println("hi!" + this.name); } } public class MyApp { public static void main(String[] args){ User tom; tom = new User("Tom"); System.out.println(tom.name); tom.sayHi(); } }
[vagrant@localhost java]$ javac MyApp.java
[vagrant@localhost java]$ java MyApp
Tom
hi!Tom
なるほど、何故か急に分かってきた。
classの継承
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); } } 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(); } }
@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 void sayHi(){ System.out.println("[admin]hi!" + this.name); } } 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(); } }
[vagrant@localhost java]$ javac MyApp.java
[vagrant@localhost java]$ java MyApp
Tom
hi!Tom
bob
[admin]hi!bob
hello!bob
ほうほう