Skip to content

Instantly share code, notes, and snippets.

@tachiba
Created May 17, 2011 09:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tachiba/976209 to your computer and use it in GitHub Desktop.
Save tachiba/976209 to your computer and use it in GitHub Desktop.
Books
package may.d17;
public class Book {
// static => クラスフィールド
public static String material;
public static String shuppan;
// 非static => インスタンスフィールド
public String author;
public String title;
public Book(String a, String b){
title = a;
author = b;
}
// static => クラスメソッド
public static String getMaterial(){
return "素材:" + material;
}
// 非static => インスタンスメソッド
public void print(){
System.out.println("タイトル:" + title + ", 著者:" + author);
}
}
package may.d17;
public class BookTest {
public static void main(String[] args){
// staticなフィールドはクラスを定義にしたときに、作られている。
// (material)
// クラスフィールド(クラス1つにたいしてひとつしかない)
Book.material = "金属";
Book.shuppan = "小学館";
Book b1 = new Book("Javaレッスン", "結城浩");
// b1 => (title, author)
Book b2 = new Book("ハリーポッター", "J・K・ローリング");
// b2 => (title, author)
// インスタンスフィールド(オブジェクトひとつにたしいてひとつ)
b1.title = "ほげほげ";
b1.author = "sado";
b2.author = "ちば";
// こうやってもクラスフィールドにアクセスできてしまう!
// 紛らわしい!
Book.material = "金属";
System.out.println(Book.shuppan);
System.out.println(Book.getMaterial());
b1.print();
b2.print();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment