とよぶ

歌いながらコード書いてます

Javaオブジェクト指向(1)

オブジェクト指向

ざっくりと書くので言葉のニュアンスは気にしない(でいたいっw)。

  • クラスに書けるもの3つ
    1. フィールド
    2. メソッド
    3. コンストラクタ
  • new演算子を用いてインスタンスを作成する
  • 新しいクラスを作成すると、新しいクラス型が作成されるので、下記のような宣言が可能
User user = new User();
  • オブジェクトの宣言はそのクラス型で宣言する
User user = new User();
  • フィールドとメソッドはオブジェクトがそれぞれ持っている。Userクラスがsex, year, speak()というメソッドを持っている場合に、下記のようにとしてインスタンスを作ると、user1というオブジェクトはuser1.sex, user1.year, user1.speak, を使用することが可能で、user2はuser2.sex, user2.year, user2.speakを使用可能。わかりやすく言うとクラスがたいやきの型で、インスタンスが焼き上がったそれぞれのたい焼き。
User user1 = new User();
User user2 = new User();
User user = new User("takasing104");//インスタンス作成
public String username;
public User(String username) {
    this.username = username;//ここではthis=user→user.usernameに"taking104"を代入している。
}
  • インスタンス名.フィールド・メソッドを実行→そのフィールドやメソッドが見当たらなかったらJavaはクラスフィールド・メソッドを参照しに行く。下記において、を呼び出すような時警告は出るがコンパイルは通る。
public class Hoge {
	public static void main(String[] args) {
		Box box1 = new Box("チョコビ", 5);
		Box box2 = new Box("空想科学読本", 1);
		
		Box.key = new String("ひらけごま");
		Box.look(box1, "ヒラケゴマ");
		Box.look(box2, "ひらけごま");
		
		Box.key = new String("チチンプイプイ");
		Box.look(box1, "チチンプイプイ");
		Box.look(box2, "ちちんぷいぷい");
	}

}
public class Box {

	public static String key;
	public String item;
	public int num;
	
	// constructors
	public Box() {
	}
	public Box(String item, int num) {
		this.item = item;
		this.num = num;
	}

	public void look(String word) {
		System.out.println(word + item + "が" + num + "つ見える");
	}
	public static void look(Box box, String key) {
                //←box.keyはBox.keyであるべきだが、一応コンパイル可能
		if (key.equals(box.key)) { 
			System.out.println("箱の中には" + box.item + "が" + box.num + "つある");
		} else {
			System.out.println("キーワードが違うよ");
		}
	}
}
  • String型は特殊、比較時は必ずequalsメソッドを使う。String型ではコンストラクタを使わずに初期化するとコンスタントプールにある文字列を共有する(つまり同一オブジェクトを持つ)。
String s1 = "Hello";
String s2 = "Hello";
String s3 = new String("Hello");
String s4 = new String("Hello");
System.out.println(s1 == s2);//値比較
System.out.println(s3 == s4);//メモリアドレスを比較している
System.out.println(s1.equals(s2));//参照先のオブジェクト比較
System.out.println(s3.equals(s4));
true
false
true
true


今回はこの程度。
変数とかメソッドとかその他説明省きましたが、随時更新して行く(かもっ)。