Programming with Java, part 3

記事
IT・テクノロジー

About inheritance

Triangle is a kind of figure, so I created a parent class
of Triangle class. That is the Figure class below.

------------------------ Figure.java ----------------------------
public class Figure {
 // Member variables
 private int iArea;

 // getter
 public int getArea() {
  return this.iArea;
 }

 // setter
 public void setArea(int area) {
  this.iArea = area;
 }
}
---------------------------------------------------------------------

---------------------- Triangle.java ----------------------------
public class Triangle extends Figure{
 // Member variables
 private int iBottom;
 private int iHeight;

 // Constructor
 public Triangle(int bottom, int height) {
  this.iBottom = bottom;
  this.iHeight = height;
  super.setArea(calculateArea(bottom, height));
 }

 // Calculate the area of the triangle.
 private int calculateArea(int bottom, int height){
  return bottom * height / 2;
 }
}
---------------------------------------------------------------------

-------------------------- Main.java ----------------------------
import java.util.Scanner;

public class Main {
 public static void main(String args[]) throws Exception{
  System.out.println("How long is the bottom?");
  Scanner sc = new Scanner(System.in);
  int iBottom = sc.nextInt();      // Input the bottom.
  System.out.println("How long is the height?");
  int iHeight = sc.nextInt();       // Input the height.

  Triangle triangle = new Triangle(iBottom, iHeight);
  int iArea = triangle.getArea();
  System.out.println("Area = " + iArea);
 }
}
---------------------------------------------------------------------

Since every figure has an area, I defined iArea as a
private member variable of the Figure class. If you want to
set a value for this variable, you use the setArea method
(setter).
Next, let's take a look at Triangle.java. Triangle class inherits
the Figure class with "extends" in the "public class Triangle
extends Figure" line. Last time I defined iArea as a member
variable of the Triangle class, but I moved it to the Figure class.
Also, the result of calculating the area with the constructor
is set by calling the Figure class setter like super.setArea.

Furthermore, I added a square class to better understand
the goodness of inheritance. That is the Square class below.
Along with this, the Main class has also been modified.

---------------------- Square.java -----------------------------
public class Square extends Figure{
 // Member variables
 private int iOneSide;

 // Constructor
 public Square(int oneSide) {
  this.iOneSide = oneSide;
  super.setArea(calculateArea(oneSide));
 }

 // Calculate the area of the triangle.
 private int calculateArea(int oneSide){
  return oneSide * oneSide;
 }
}
---------------------------------------------------------------------

------------------------- Main.java -----------------------------
import java.util.Scanner;

public class Main {
 public static void main(String args[]) throws Exception{
  System.out.println("Which area do you want to calculate?");
  System.out.println("If you enter 1, it's a triangle.");
  System.out.println("If you enter 2, it's a square.");
  Scanner sc = new Scanner(System.in);
  int iSelectResult = sc.nextInt();      // 1:triangle, 2:square
  int iArea = 0;

  // Triangle
  if(iSelectResult == 1) {
   System.out.println("How long is the bottom?");
   int iBottom = sc.nextInt();      // Input the bottom.
   System.out.println("How long is the height?");
   int iHeight = sc.nextInt();       // Input the height.
   Triangle triangle = new Triangle(iBottom, iHeight);
   iArea = triangle.getArea();

  // Square
  } else if(iSelectResult == 2) {
   System.out.println("How long is the one side?");
   int iOneSide = sc.nextInt();      // Input the one side.
   Square square = new Square(iOneSide);
   iArea = square.getArea();

  // Other
  } else {
   System.out.println("Please enter 1 or 2.");
   return;
  }
  System.out.println("Area = " + iArea);
 }
}
---------------------------------------------------------------------

Square.java defines the length of one side of a square
as a member variable. The Square class also inherits
from the Figure class, so you don't need to define an area
in a member variable.
Also, in Main.java, after the message is displayed,
you enter either 1 or 2 to decide whether to calculate the area
of the triangle or the square. If you enter 1, it's a triangle,
if you enter 2, it's a square. You can get the area from each
object with the getArea method.


If there are properties and processes that are common to
each other, such as the area of a figure, you may want to define
them in the parent class to reduce waste and make the
program easier to read. On the other hand, you may want to
define the different properties and processes in child classes
(like Triangle class and Square class in this case).


[Japanese]

継承について

三角形は図形の一種ですので、Triangleクラスの親クラスを作成してみました。それが下記のFigureクラスになります。

------------------------ Figure.java ----------------------------
public class Figure {
 // Member variables
 private int iArea;

 // getter
 public int getArea() {
  return this.iArea;
 }

 // setter
 public void setArea(int area) {
  this.iArea = area;
 }
}
---------------------------------------------------------------------

---------------------- Triangle.java ----------------------------
public class Triangle extends Figure{
 // Member variables
 private int iBottom;
 private int iHeight;

 // Constructor
 public Triangle(int bottom, int height) {
  this.iBottom = bottom;
  this.iHeight = height;
  super.setArea(calculateArea(bottom, height));
 }

 // Calculate the area of the triangle.
 private int calculateArea(int bottom, int height){
  return bottom * height / 2;
 }
}
---------------------------------------------------------------------

-------------------------- Main.java -----------------------------
import java.util.Scanner;

public class Main {
 public static void main(String args[]) throws Exception{
  System.out.println("How long is the bottom?");
  Scanner sc = new Scanner(System.in);
  int iBottom = sc.nextInt();      // Input the bottom.
  System.out.println("How long is the height?");
  int iHeight = sc.nextInt();       // Input the height.

  Triangle triangle = new Triangle(iBottom, iHeight);
  int iArea = triangle.getArea();
  System.out.println("Area = " + iArea);
 }
}
---------------------------------------------------------------------

どんな図形も面積を持っていますので、Figureクラスのメンバ変数にprivateでiAreaを定義しました。この変数に値を設定するには、setAreaメソッド(setterといいます)を利用します。
次にTriangle.javaを見てみましょう。「public class Triangle extends Figure」のextendsによって、Figureクラスを継承します。前回はTriangleクラスのメンバ変数にiAreaを定義しましたが、Figureクラスに移動したのでありません。また、コンストラクタで面積を計算した結果を、super.setAreaのようにFigureクラスのsetterを呼び出して設定しています。

継承の良さをより理解するために、正方形のクラスを追加しました。それが下記のSquareクラスです。これに伴い、Mainクラスも修正したものになっています。

---------------------- Square.java -----------------------------
public class Square extends Figure{
 // Member variables
 private int iOneSide;

 // Constructor
 public Square(int oneSide) {
  this.iOneSide = oneSide;
  super.setArea(calculateArea(oneSide));
 }

 // Calculate the area of the triangle.
 private int calculateArea(int oneSide){
  return oneSide * oneSide;
 }
}
---------------------------------------------------------------------

------------------------- Main.java -----------------------------
import java.util.Scanner;

public class Main {
 public static void main(String args[]) throws Exception{
  System.out.println("Which area do you want to calculate?");
  System.out.println("If you enter 1, it's a triangle.");
  System.out.println("If you enter 2, it's a square.");
  Scanner sc = new Scanner(System.in);
  int iSelectResult = sc.nextInt();      // 1:triangle, 2:square
  int iArea = 0;

  // Triangle
  if(iSelectResult == 1) {
   System.out.println("How long is the bottom?");
   int iBottom = sc.nextInt();     // Input the bottom.
   System.out.println("How long is the height?");
   int iHeight = sc.nextInt();      // Input the height.
   Triangle triangle = new Triangle(iBottom, iHeight);
   iArea = triangle.getArea();

  // Square
  } else if(iSelectResult == 2) {
   System.out.println("How long is the one side?");
   int iOneSide = sc.nextInt();      // Input the one side.
   Square square = new Square(iOneSide);
   iArea = square.getArea();

  // Other
  } else {
   System.out.println("Please enter 1 or 2.");
   return;
  }
  System.out.println("Area = " + iArea);
 }
}
---------------------------------------------------------------------

Square.javaは、正方形の一辺の長さをメンバ変数に定義しています。SquareクラスもFigureクラスを継承しているので、メンバ変数に面積を定義する必要はありません。
また、Main.javaではメッセージが表示された後、三角形の面積を計算するか、正方形にするかを、1か2のどちらかを入力して決定します。1を入力すると三角形、2を入力すると正方形です。それぞれのオブジェクトからgetAreaメソッドで面積を取得できます。


図形の面積のように、共通して持っている性質や処理などがあれば、親クラスで定義した方が無駄を省くことができ、プログラムも読みやすくなります。一方、異なる性質や処理は子クラス(今回の場合はTriangleやSquare)に定義すれば良いのです。
サービス数40万件のスキルマーケット、あなたにぴったりのサービスを探す