------------------------------------------------------------------------------------------- ■ 継承 実例A --- 学生の身体測定結果から体脂肪率を自動計算して、肥満度を判断するプログラム ------------------------------------------------------------------------------------------- package school; public class Student { private int no; private String name; //コンストラクタ(newの時に呼ばれるクラス名同名メソッド・関数) public Student(int _no, String _name){ no = _no; name = _name; } //データを個別に設定、取得するメソッド public String getName() { return name; } public int getNo() { return no; } public void setName(String string) { name = string; } public void setNo(int i) { no = i; } }// Studentクラスの終わり --------------------------------------------------------------------------------------- // Studentクラスとデータ内容が重複するので、継承してみる package school; public class StudentBMI extends Student { private double tall; private double weight; public StudentBMI(int _no, String _name, int _tall, int _weight) { super(_no, _name); tall = _tall; weight = _weight; } //体脂肪率を計算して、少数で返すメソッド public double calcBMI(){ double bmi = weight / (tall/100 * tall/100); return bmi; } //体脂肪率の計算結果から、肥満度を文字列で返すメソッド public String judgeBMI(){ String judge = null; if(17 <= calcBMI() && calcBMI() <=23){ judge ="標準"; }else if(24 <= calcBMI() && calcBMI() <=29){ judge ="肥満傾向あり"; }else if(calcBMI()>=30){ judge ="肥満"; }else{ judge ="痩せ気味"; } return judge; } //全データを一覧で表示するメソッド public void showAllData() { //各データを文字列連結する String alldata = "NO:" + super.getNo() + "\n" + "氏名:" + super.getName() + "\n" + "身長:" + tall + "\n" + "体重:" + weight + "\n" + "体脂肪率:" + calcBMI() + "\n" + "肥満度:" + judgeBMI()+ "\n" + "-------------------------"; System.out.println(alldata); } }// StudentBMIクラスの終わり ----------------------------------------------------------------------------------------- //実行クラス package school; public class BMI_Main { public static void main(String[] args){ StudentBMI sb = new StudentBMI(11, "鈴木祐介",176,65); sb.showAllData(); } }//実行クラス BMI_Mainの終わり ******************************************************* **** 実行結果 ***************************************** NO:11 氏名:鈴木祐介 身長:176.0 体重:65.0 体脂肪率:20.983987603305785 肥満度:標準 ------------------------- *******************************************************