プログラミング初級(java)javaは、様々なクラスを連携させて動作するもの...

Post on 18-Jan-2020

1 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

プログラミング初級(Java)

第12回メッセージのやりとり

白銀純子

Copyright (C) Junko Shirogane, Waseda University 2019, All rights reserved. 1

Copyright (C) Junko Shirogane, Waseda University 2019, All rights reserved. 2

メッセージのやりとり

第12回の内容

メソッドの作り方・使い方

Copyright (C) Junko Shirogane, Waseda University 2019, All rights reserved. 35

Copyright (C) Junko Shirogane, Waseda University 2019, All rights reserved. 36

プログラム中で行われる処理の手順をまとめたもの

複数の処理をまとめて、1つの名前を付けたもの

オブジェクトがプログラム内で担当する処理をまとめたもの

メソッド名、引数、戻り値(返り値)という構成

メソッド名: メソッドの名前

引数: メソッドに渡す情報(計算等の処理の材料にするデータ)

処理の材料にするデータのみ、引数として定義

戻り値(返り値): メソッドの内容を実行したときの処理結果

多くの場合、戻り値を変数に代入して利用する

「変数名 = メソッド」で、変数に戻り値が代入される

メソッド

メソッドのイメージ

Copyright (C) Junko Shirogane, Waseda University 2019, All rights reserved. 37

引数 引数引数

戻り値

メソッドに対して与えるデータ

ごにょごにょ...

メソッド

メソッドの処理結果

Copyright (C) Junko Shirogane, Waseda University 2019, All rights reserved. 38

Integer.parseInt(str)

メソッド名: Integer.parseInt

引数: str(String型)

戻り値: 「str」をint型に変換したデータ

戻り値をint型の変数に代入して利用する

メソッド(例)(1)

「num = Integer.parseInt(str)」で、変数「num」に、文字列をint型のデータに変換したものが代入される

与えられた引数をint型に変換した結果

ごにょごにょ...

Integer.parseInt

String型のデータ

Copyright (C) Junko Shirogane, Waseda University 2019, All rights reserved. 39

str.substring(m, n)

メソッド名: substring

引数: m(int型) と n(int型)

戻り値: 「str」のm番目からn番目までの文字で作った部分文字列

戻り値をString型の変数に代入して利用する

メソッド(例)(2)

「subStr = str.substring(m, n)」で、変数「subStr」に、strの部分文字列が代入される

fromとtoのインデックスから作られた部分文字列

ごにょごにょ...

substring

部分文字列のインデックス(from) 部分文字列のインデックス(to)

Copyright (C) Junko Shirogane, Waseda University 2019, All rights reserved. 40

今回定義するのは の部分

メソッドを作る(メソッドの定義)(1)

public static 戻り値のデータ型 メソッド名(引数) {

メソッドでの処理内容return 処理結果;

}

メソッドを作るときのお約束➢ 「static」キーワードは、メソッドの目的によってつけない場合とつける場合あり

ごにょごにょ...

Copyright (C) Junko Shirogane, Waseda University 2019, All rights reserved. 41

Javaは、様々なクラスを連携させて動作するもの

アクセス修飾子: クラス同士を連携させたときに、他のクラスから利用できるか否かを示すもの

public: 他のクラスから利用可能←今回は、他のクラスから利用するので、とりあえずpublicでOK

protected: 限られた範囲で、他のクラスから利用可能

private: 他のクラスからは利用不可

アクセス修飾子

Copyright (C) Junko Shirogane, Waseda University 2019, All rights reserved. 42

「static」がついているメソッド(クラスメソッド)

「クラス名.メソッド」の形式で呼び出し可能(「オブジェクト名.メソッド」の形式でも可能)

staticつきのメソッド内部で、同じクラスで定義されているメソッドを呼び出すときは、そのメソッドにもstaticが必要

mainメソッドから呼び出すときは、「static」がついている必要

メソッドを定義しているクラスのインスタンス変数を利用することは不可能(クラス変数は利用可能)

「static」のあるなし(1)

オブジェクトによって処理結果の変わらないメソッドはstaticをつけて良い(つけないメソッドにしても良い)

Copyright (C) Junko Shirogane, Waseda University 2019, All rights reserved. 43

「static」がついていないメソッド(インスタンスメソッド)

必ず「オブジェクト名.メソッド」の形式で呼び出し(「クラス名.メソッド」の形式では呼び出し不可能)

staticなしのメソッド内部で、同じクラスで定義されているメソッドを呼び出すときは、そのメソッドはstaticはついていても、ついていなくても良い

staticなしのメソッド内部で、同じクラスで定義されているフィールドは、インスタンス変数・クラス変数とも利用可能

「static」のあるなし(2)

オブジェクトによって処理結果の変わるメソッド(同じクラスで定義されているstaticなしのフィールドを処理に使うなど)は、必ずstaticなし

Copyright (C) Junko Shirogane, Waseda University 2019, All rights reserved. 44

クラスに関連づけるメソッドとオブジェクトに関連づけるメソッドの2種類

メソッドの定義

public static 戻り値のデータ型 メソッド名(引数) {

メソッドでの処理内容return 処理結果;

}

クラスに関連づけるメソッドの定義のテンプレート

public 戻り値のデータ型 メソッド名(引数) {

メソッドでの処理内容return 処理結果;

}

オブジェクトに関連づけるメソッドの定義のテンプレート

違い: 「static」キーワードがついているかいないか

Copyright (C) Junko Shirogane, Waseda University 2019, All rights reserved. 45

今回定義するのは の部分

メソッドを作る(メソッドの定義)(2)

public static 戻り値のデータ型 メソッド名(引数) {

メソッドでの処理内容return 処理結果;

}

戻り値は1つだけ

ごにょごにょ...

メソッドを作る(メソッドの定義)(3)

Copyright (C) Junko Shirogane, Waseda University 2019, All rights reserved. 46

public static 戻り値のデータ型 メソッド名(引数) {

メソッドでの処理内容return 処理結果;

}

メソッドの名前(名前の付け方は、クラス名や変数名と同じ)

Javaの命名規則としては...

➢ 先頭の単語は動詞にする➢ 複数の単語を連結するときは、先頭の単語はすべて小文字、2つ目以降の単語は先頭の文字のみ大文字、あとは小文字✓ 変数と同じ

メソッドを作る(メソッドの定義)(4)

Copyright (C) Junko Shirogane, Waseda University 2019, All rights reserved. 47

public static 戻り値のデータ型 メソッド名(引数) {

メソッドでの処理内容return 処理結果;

}

➢「引数のデータ型 引数の変数名」と書く➢引数はいくつあっても良い(「,」で区切る)

➢データ型はそれぞれ異なってもかまわない

Copyright (C) Junko Shirogane, Waseda University 2019, All rights reserved. 48

引数の定義は、一見変数宣言のよう

実際、メソッド内で使う変数の宣言とも言える

引数の定義の注意

but…通常の変数宣言とは違う!

➢ 必ず「データ型 変数名」のセットで書かなければならない

public int sum(int num1, int num2, int num3) {

int result;

result = num1 + num2 + num3;

return result;

}

public int sum(int num1, num2, num3) {

int result;

result = num1 + num2 + num3;

return result;

}

メソッドを作る(メソッドの定義)(5)

Copyright (C) Junko Shirogane, Waseda University 2019, All rights reserved. 49

※「処理内容」の部分では、「引数」で定義した変数を変数として利用できる

public int sum(int num1, int num2) {

int result;

result = num1 + num2;

return result;

}

public static 戻り値のデータ型 メソッド名(引数) {

メソッドでの処理内容return 処理結果;

}

処理内容は何を書いても良い(if, for, while, ...)

メソッドを作る(メソッドの定義)(6)

Copyright (C) Junko Shirogane, Waseda University 2019, All rights reserved. 50

public static 戻り値のデータ型 メソッド名(引数) {

メソッドでの処理内容return 処理結果;

}

➢「処理結果」を出すという意味(「変数名 = メソッド名(引数)」と 書くと、「変数名」の中に処理結果が代入される)

➢この文でメソッドの内容が終わる(この後には文を書かないこと)

➢処理結果のデータ型と戻り値のデータ型は同じもの

Copyright (C) Junko Shirogane, Waseda University 2019, All rights reserved. 51

戻り値のデータ型とreturn文で返すデータ型は同じでなくてはならない

return文

public int sum(int num1, int num2) {

int result;

result = num1 + num2;

return result;

}

public String sum(int num1, int num2) {

int result;

result = num1 + num2;

return result;

}

データ型が同じ

違うデータ型

Copyright (C) Junko Shirogane, Waseda University 2019, All rights reserved. 52

メソッドの作成例

public double average( int num1, int num2, int num3 ) {

double result;

result = (double) (num1 + num2 + num3) / 3;

return result;

}

引数に与えられた3つの数の平均を求めるメソッド

処理結果を「double」型で出す

「return」で、「結果を出す」という意味(「return」の後に書く処理結果のデータ型は、戻り値のデータ型と

同じにすること)

引数の定義

処理内容

Copyright (C) Junko Shirogane, Waseda University 2019, All rights reserved. 53

フィールドの変数宣言の下に作る

上に作っても良い

メソッドを作る場所

import java.io.*;

import java.lang.*;

public class Student {

String address, name, tel;

int studentNumber, english, math, language;

}

メソッドの定義を書く場所

メソッドの作成例

Copyright (C) Junko Shirogane, Waseda University 2019, All rights reserved. 54

public class Sample {

String name, address;

int english, math, language;

public double average(int num1, int num2, int num3) {

double result;

result = (double) (num1 + num2 + num3) / 3;

return result;

}

}

メッセージのやり取り

Copyright (C) Junko Shirogane, Waseda University 2019, All rights reserved. 55

Copyright (C) Junko Shirogane, Waseda University 2019, All rights reserved. 56

メッセージ = あるクラスで定義されたメソッドを呼び出すこと

「オブジェクト名.メソッド」(または「クラス名.メソッド」)の形式で呼び出し

ただし、メソッドを定義している同じクラス内で呼び出すときは、オブジェクト名やクラス名は省略

Ex1. str.substring(m, n)

Stringクラスに定義されている「substring」というメソッドを呼び出し(strはStringクラスのオブジェクト = String型の変数)

Ex2. Integer.parseInt(str)

Integerクラスに定義されている「parseInt」というメソッドを呼び出し(strはStringクラスのオブジェクト = String型の変数)

メッセージ

Copyright (C) Junko Shirogane, Waseda University 2019, All rights reserved. 57

1.各クラスでメソッドを定義する

2.オブジェクト同士でメソッドを呼び出しあう

メッセージのやり取りをするには

Copyright (C) Junko Shirogane, Waseda University 2019, All rights reserved. 58

あるクラス(名前: ClassA)で定義されているメソッドを...

別のクラスから呼び出す場合

同じクラス(ClassA)から呼び出す場合: 「オブジェクト名.」や「クラス名.」は不要

メソッド名 + 引数のみでOK

オブジェクト同士でのメソッドの呼び出し

メソッドがインスタンスメソッドの場合: ClassAのオブジェクト名.メソッド

メソッドがクラスメソッドの場合: ClassA.メソッド

メソッドの定義とメッセージでの処理の流れ(例)(1)

Copyright (C) Junko Shirogane, Waseda University 2019, All rights reserved. 59

// 商品の値段管理public class Product {

int price;

// 商品の金額計算(discount: 割引率, tax: 税率)

public int calcAmount(double discount, double tax) {

double doubleAmount;

int intAmount;

doubleAmount = (double) price * (1 - discount) * (1 + tax);

intAmount = (int) doubleAmount;

return intAmount;

}

}

メソッドの定義➢ 「price」はフィールド変数

// 割引率と税率を設定して、商品の金額計算public class ProductManage {

public static void main(String[] args) {

int amount;

Product pro = new Product();

// 割引率: 0.2 (2割引)

amount = pro.calcAmount(0.2, 0.08);

}

}

ProductManage.java Product.java

メソッドの定義とメッセージでの処理の流れ(例)(2)

Copyright (C) Junko Shirogane, Waseda University 2019, All rights reserved. 60

// 商品の値段管理public class Product {

int price;

// 商品の金額計算(discount: 割引率, tax: 税率)

public int calcAmount(double discount, double tax) {

double doubleAmount;

int intAmount;

doubleAmount = (double) price * (1 - discount) * (1 + tax);

intAmount = (int) doubleAmount;

return intAmount;

}

}

// 割引率と税率を設定して、商品の金額計算public class ProductManage {

public static void main(String[] args) {

int amount;

Product pro = new Product();

// 割引率: 0.2 (2割引)

amount = pro.calcAmount(0.2, 0.08);

}

}

ProductManage.java Product.java

引数には具体的な値または変数を書く(引数の順番は、メソッドを作ったときの順番と同じに)

calcAmountというメソッドを呼び出す

メソッドの定義とメッセージでの処理の流れ(例)(3)

Copyright (C) Junko Shirogane, Waseda University 2019, All rights reserved. 61

// 割引率と税率を設定して、商品の金額計算public class ProductManage {

public static void main(String[] args) {

int amount;

Product pro = new Product();

// 割引率: 0.2 (2割引)

amount = pro.calcAmount(0.2, 0.08);

}

}

ProductManage.java Product.java

// 商品の値段管理public class Product {

int price;

// 商品の金額計算(discount: 割引率, tax: 税率)

public int calcAmount(double discount, double tax) {

double doubleAmount;

int intAmount;

doubleAmount = (double) price * (1 - discount) * (1 + tax);

intAmount = (int) doubleAmount;

return intAmount;

}

}

処理の流れ1. mainメソッドで、calcAmountメソッドの引数に0.2と0.08を指定する2. 0.2と0.08というデータがcalcAmountメソッドの引数の変数「discount」と「tax」にそれぞれ代入される3. calcAmountメソッド内で引数の値を使って計算され、変数intAmountに結果が代入される4. calcAmountメソッドの変数intAmountの値がmainメソッドの変数amountに代入される

メソッドの呼び出し(例)(1)

Copyright (C) Junko Shirogane, Waseda University 2019, All rights reserved. 62

public class Student {

String address, name, tel;

int studentNumber, english, math, language;

static String schoolName = "早稲田高校";

public void setEnglish(int score) {

english = score;

}

public static String getSchoolName() {

return schoolName;

}

... 略 ...

}

public class StudentManage {

public static void main(String[] args) {

Student[] info = new Student[50];

String scName;

info[0] = new Student();

info[0].setEnglish(80);

scName = Student.getSchoolName();

... 略 ...

}

}

※クラス変数は、宣言と同時に値を代入してOK

メソッドの呼び出し(例)(2)

Copyright (C) Junko Shirogane, Waseda University 2019, All rights reserved. 63

public class Student {

String address, name, tel;

int studentNumber, english, math, language;

static String schoolName = "早稲田高校";

public void setEnglish(int score) {

english = score;

}

public static String getSchoolName() {

return schoolName;

}

... 略 ...

}

public class StudentManage {

public static void main(String[] args) {

Student[] info = new Student[50];

String scName;

info[0] = new Student();

info[0].setEnglish(80);

scName = Student.getSchoolName();

... 略 ...

}

}

インスタンスメソッドの定義

インスタンスメソッドの呼び出し

メソッドの呼び出し(例)(3)

Copyright (C) Junko Shirogane, Waseda University 2019, All rights reserved. 64

public class Student {

String address, name, tel;

int studentNumber, english, math, language;

static String schoolName = "早稲田高校";

public void setEnglish(int score) {

english = score;

}

public static String getSchoolName() {

return schoolName;

}

... 略 ...

}

public class StudentManage {

public static void main(String[] args) {

Student[] info = new Student[50];

String scName;

info[0] = new Student();

info[0].setEnglish(80);

scName = Student.getSchoolName();

... 略 ...

}

}

クラスメソッドの定義

クラスメソッドの呼び出し

Copyright (C) Junko Shirogane, Waseda University 2019, All rights reserved. 65

データ定義のクラスは、ある1人の人またはある1つのものが、どういうデータを持ち、プログラム内でどのような役割を担当するか、を表すもの

処理のクラスは、データ定義のクラスのあらゆるオブジェクトに対する様々な処理をするクラス

クラスの役割分担(1)

どのクラスにどういうメソッドを定義するか? は、クラスの役割を考える必要

Copyright (C) Junko Shirogane, Waseda University 2019, All rights reserved. 66

クラスの役割分担(2)

public class Student {

String name;

int english[];

public void searchOver85() {

int i;

for(i = 0; i < 30; i = i + 1) {

if (english[i] >= 85) {

System.out.println(name + "さん: " + english[i] + "点");

}

}

}

}

public class StudentManage {

public static void main(String[] args) {

Student st = new Student();

st.searchOver85();

}

}

Ex. 学内英語力コンテストに、A組代表として参加する人を選ぶため、英語の得点85点以上の生徒を出力したい

1人の生徒(例えば早稲田太郎さん)が、A組の人全員の英語の得点を調べる処理

早稲田太郎さんは、A組の人全員の得点を知っている

普通はありえない!

Copyright (C) Junko Shirogane, Waseda University 2019, All rights reserved. 67

クラスの役割分担(3)

public class Student {

String name;

int english;

}

public class StudentManage {

public static void main(String[] args) {

Student st[] = new Student[30];

...... 略 ......

int i;

for(i = 0; i < 30; i = i + 1) {

if (sti[i].english >= 85) {

System.out.println(st[i].name + "さん: " + st[i].english + "点");

}

}

}

}

Ex. 学内英語力コンテストに、A組代表として参加する人を選ぶため、英語の得点85点以上の生徒を出力したい

処理クラスは、先生や成績管理システムのイメージ

データ定義のクラス・処理クラスが、どの処理を担当するのが自然か?を考えよう!

Copyright (C) Junko Shirogane, Waseda University 2019, All rights reserved. 68

別の考え方をすると…オブジェクト指向では、プログラム内に登場人物が2人以上

クラスの役割分担(4)

public class Student {

String name;

int english;

}

public class StudentManage {

public static void main(String[] args) {

Student st[] = new Student[30];

...... 略 ......

int i;

for(i = 0; i < 30; i = i + 1) {

if (sti[i].english >= 85) {

System.out.println(st[i].name + "さん: " + st[i].english + "点");

}

}

}

}

Ex. 学内英語力コンテストに、A組代表として参加する人を選ぶため、英語の得点85点以上の生徒を出力したい

登場人物: StudentManageさんとStudentさん➢ StudentManageさんの役割: 英語の得点85点以上の人を探す➢ Studentさんの役割: 自分自身の名前と得点の情報を知っている

Copyright (C) Junko Shirogane, Waseda University 2019, All rights reserved. 69

別の考え方をすると…オブジェクト指向では、プログラム内に登場人物が2人以上

クラスの役割分担(5)

登場人物: ProductManageさんとProductさん➢ ProductManageさんの役割: Productさんに対して、「今の割引率と税率はこれとこれだから、あなたの金額の計算をして!」とお願いする

➢ Studentさんの役割: ProductManageさんから頼まれた計算をして、結果をProductManageさんに伝える

// 割引率と税率を設定して、商品の金額計算public class ProductManage {

public static void main(String[] args) {

int amount;

Product pro = new Product();

// 割引率: 0.2 (2割引)

amount = pro.calcAmount(0.2, 0.08);

}

}

// 商品の値段管理public class Product {

int price;

// 商品の金額計算(discount: 割引率, tax: 税率)

public int calcAmount(double discount, double tax) {

double doubleAmount;

int intAmount;

doubleAmount = (double) price * (1 - discount) * (1 + tax);

intAmount = (int) doubleAmount;

return intAmount;

}

}

Ex. 商品の金額計算をしたい

top related