Chapter 4. OOP Application

ITSS Java Programming  CAO Tuan­Dung, HUT

1

Inheritance

 Mechanism to create new classes using existing classes

 The existing class is called the parent class, or superclass,

or base class

 The derived class is called the child class or subclass

 As the name implies, the child inherits characteristics of the

parent

 That is, the child class inherits the methods and data defined

by the parent class

2

Benefit of Inheritance

 Reusability

 Once a behavior (method) is defined in a super class,

that behavior is automatically inherited by all subclasses   Thus, you write a method only once and it can be used by

all subclasses.

 Once a set of properties (fields) are defined in a super  class, the same set of properties are inherited by all  subclasses

 A class and its children share common set of properties  A subclass only needs to implement the differences

between itself and the parent.

3

Inheritance

Superclass Account

Class that defines basic function of Account

All the behaviors of superclass(attribute, operation, relation) are inherited to the sub-class

Sub-class IntegratedAccount

Basic function of Account

+

Class that defines original behavior

Superclass Account

4

Definition of sub­class

 To derive a child class, we use the extends keyword.  Syntax:

[Modifier] class Sub­class_name extends SuperClass_name{

Definition of member variable to add Method definition to add or redefine

}

// Integrated account class (sub­class)

// Account class (superclass)

class IntegratedAccount extends Account {

class Account {

int limitOverdraft; //Borrowing amount limit

String name; //Account name

int overdraft; //Borrowing amount

int balance; //Balance

void loan(int money){…} //Borrowing()

void display(){…..}

void display(){…..}        // Display

// Display

}

}

IntegratedAccount obj= new IntegratedAccount();

5

Another example

public class Person {

protected String name;  protected String address;  /** * Default constructor   */  public Person(){

System.out.println(“Inside Person:Constructor”); name = ""; address = "";

} . . . . }

6

Object of sub­class

superclass part

name

balance

display(){…}

In the object of the sub­ class, there are the member  variable and the method  that were defined by the  superclass, and the  member variable and the  method that were added by  the sub­class. object of sub­class

limitOverdraft

overdraft

display2(){…}

loan(){…}

7

Example: Inheritance.java

// Account class class Account { // Member variable private String name;        // Account name private int balance; // Balance // Value setting Method public void setData(String pName, int

pInitialBalance) { name = pName; balance = pInitialBalance;

}

limitOverdraft = pLimitOverdraft; overdraft = 0;

} public void loan(int pOverdraft) { if((overdraft+pOverdraft) <= limitOverdraft) {

// Value setting Method public void display() { System.out.print("Account name : System.out.println(“\tBalance :

" + name); " + balance +

“VND");

overdraft += pOverdraft;

} }

}  else { System.out.println(“Total of borrowing  exceeds borrowing amount limit ");

}  }

// Integrated account class class IntegratedAccount extends Account { // Additional member variable private int limitOverdraft; // Borrowing amount limit private int overdraft;      // Borrowing amount // Additional method // // Setting of borrowing amount limit Method public void setLimitOverdraft(int pLimitOverdraft) {

8

Inheritance.java

// Display of value 2 Method public void display2() {

"+ limitOverdraft + “VND");

System.out.println(“\t\t Borrowing amount limit : System.out.println(“\t\t Borrowing amount :

" + overdraft + “VND");

}

}

// Application class Exercise of inheritance class Inheritance {

public static void main(String args[]) {

// Generation of sub­class’s object IntegratedAccount obj = new IntegratedAccount(); // Method call of superclass (Message transmission)  obj.setData(“Duc Binh", 100000); obj.display(); // Method call of sub­class (Message transmission) obj.setLimitOverdraft(500000); obj.loan(200000); obj.display2();

}

}

9

Override

 Redefine by the subclass the method is defined by

the super class.

 A child class can override the definition of an

inherited method in favor of its own

 The new method must have the same signature as  the parent's method, but can have a different body

 The type of the object executing the method

determines which version of the method is invoked

10

Override

object of sub­class

// Account class class Account { .. .. void display() {

superclass part

//processingA;

void display(){…}

} } class IntegratedAccount { .. .. void display() {

//processingB;

} }

void display(){…}

11

Example: Overriden.java

// Account class class Account { // Member variable private String name;        // Account name private int balance; // Balance // Value setting Method public void setData(String pName, int

pInitialBalance) { name = pName; balance = pInitialBalance;

}

limitOverdraft = pLimitOverdraft; overdraft = 0;

} public void loan(int pOverdraft) { if((overdraft+pOverdraft) <= limitOverdraft) {

// Value setting Method public void display() { System.out.print("Account name : System.out.println(“\tBalance :

" + name); " + balance +

“VND");

overdraft += pOverdraft;

} }

}  else { System.out.println(“Total of borrowing  exceeds borrowing amount limit ");

}  }

// Integrated account class class IntegratedAccount extends Account { // Additional member variable private int limitOverdraft; // Borrowing amount limit private int overdraft;      // Borrowing amount // Additional method // // Setting of borrowing amount limit Method public void setLimitOverdraft(int pLimitOverdraft) {

12

Overridden.java

// Display Method (override) public void display() {

"+ limitOverdraft + “VND");

System.out.println(“\t\t Borrowing amount limit : System.out.println(“\t\t Borrowing amount :

" + overdraft + “VND");

}

}

class Overridden {

public static void main(String args[]) {

// Generation of sub­class’s object IntegratedAccount obj = new IntegratedAccount(); // Method call of superclass (Message transmission)  obj.setData(“Duc Binh", 100000); obj.display(); // Method call of sub­class (Message transmission) obj.setLimitOverdraft(500000); obj.loan(200000); obj.display();

}

}

13

this

 Keyword indicating the present object.  Specify member or method of current object  Distinguish the data member with the parameters of member functions

(which have the same name)

// Account class class Account { // Member variable private String name;        // Account name private int balance; // Balance // Value setting Method public void setData(String name, int balance) {

this.name = name; this.balance = balance;

} …. }

14

this

 Call another constructor of own class

// Account class class Account { // Member variable

// Balance

private String name;        // Account name private int balance;  public Account() { this(0);

}

public Account(int blc){

balance=blc; name=“Khong ten”;

}

…. }

‘this’(argument list) calls  overloaded constructor

15

Pass our references to other  objects

// Account class class Account { // Member variable

// Balance

private String name;        // Account name private int balance;  public Account() { this(0); ..

}

public Account(int blc){

balance=blc; AdditionalService obj= new AdditionalService(this); ..

}

…. }

16

super keyword

 Keyword indicating own superclass

name

// Balance

balance

// Account class class Account { // Member variable private String name;        // Account name private int balance;  public void display() {…} }

object of sub­class

display(){…}

class IntegratedAccount extends Account { private int limitOverdraft;  private int overdraft;

limitOverdraft

public void display() {

overdraft

// method execution of super class super.display();

}

display(){

super.display();

}

}

super

this 17

super keyword:

 Call the constructor of superclass.  A super constructor call in the constructor of a subclass will  result in the execution of relevant constructor from the super  class, based on the arguments passed.

class IntegratedAccount extends Account { private int limitOverdraft;  private int overdraft;

IntegratedAccount(String name, int balance, int

// Balance

// Account class class Account { // Member variable private String name;        // Account name private int balance;  Account(String name, int balance) {…}

limitOverdraft, int overdraft ) { // execution of constructor of the super class super (name, balance);

}

}

}

18

Example

 This example defines the constructor with the argument in  account class (Account) and the constructor without the  argument using “this” constructor. The constructor of  integrated account class. IntegratedAccount is defined by  using the constructor of the superclass. This program  introduces an example of the constructor call of own class  and the constructor call of the superclass.

19

ThisSuper.java

class Account {

private String  name;         // Account name private int balance;           // Balance // Constructor (with argument) public  Account(String name, int balance) {

this.name = name; this.balance = balance;

}

// Constructor (without argument) public  Account() {

this("Unsigned",0);           // Constructor call of own class

} // Display of value Method public  void display() {

" + name);

System.out.println("  Account name : System.out.println("      Balance :

" + balance + "Yen");

}

}

20

ThisSuper.java

// Integrated account class class IntegratedAccount extends Account {

private int limitOverdraft;   // Borrowing amount limit (additional member variable) private int overdraft;        // Borrowing amount // Constructor of sub­class public IntegratedAccount(String name, int balance, int limitOverdraft) { super(name, balance);   // Constructor call of superclass this.limitOverdraft = limitOverdraft;  this.overdraft = 0;

}

// Display value Method (override) public  void display() {

super.display();        // Call of superclass method System.out.println(“Borrowing amount limit" + limitOverdraft + "Yen"); System.out.println("   Borrowing amount" + overdraft + "Yen");

}

}

21

ThisSuper.java

// Application class ThisSuper class ThisSuper {

public static void main(String args[]) { // For constructor without argument, call constructor with argument g, g Account obj = new Account(); obj.display(); System.out.println(); // For sub­class method,  use superclass method

IntegratedAccount obj2 = new IntegratedAccount("Ichiro Suzuki",10000,50000); obj2.display(); }

}

22

Final class

 Indicating a class that can not make a sub­

class

 If a method is declared with the final

modifier, it cannot be overridden

 Example

public final class BullDog extends Dog{…}

23

Interface

 It defines a standard and public way of specifying the behavior of

classes

 Aggregate of access means (operation signature) to be published by

objects

separator class Digital clock

interface clock

Clock display(){ Digital display(); }

iClock display

Clock display() Application Program class Analog clock

Clock display(){ Analog display(); }

definition in interface

24

Definition in interface

 Syntax:

[modifier] interface interface_name {

definition of constant method signature

}

 Example

public interface MyClock{

int count; // definition of constant void display(); // method signature

}

25

Definition in interface

// Note that Interface contains just set of method // signatures without any implementations.  // No need to say abstract modifier for each method // since it assumed. public interface Relation {

public boolean isGreater( Object a, Object b); public boolean isLess( Object a, Object b); public boolean isEqual( Object a, Object b);

}

26

Inheritance of interface

 The new Interface that succeeds to the existing interface can be defined.  The method and the constant that are defined in the super interface are  inherited to the sub­interface.

public interface MyClock{

int count; // definition of constant     void display(); // method signature

}

public interface NewClock{

void setTimerMode(boolean b);     void setAlarmTime(String s)

throws

invalidTimeException;

}

inheritance

27

Why interface?

 To reveal an object's programming interface

(functionality of the object) without revealing its  implementation  This is the concept of encapsulation  The implementation can change without affecting the

caller of the interface

 The caller does not need the implementation at the

compile time

 It needs only the interface at the compile time  During runtime, actual object instance is associated with the

interface type

28

Why interface?

 To have unrelated classes implement similar

methods (behaviors)  One class is not a sub­class of another

 To model multiple inheritance

 A class can implement multiple interfaces while it

can extend only one class

29

Interface implementation

 Syntax:

[modifier] class class_name implements interface_name {

… override of method …

}

 Example

public interface MyClock{

void display(); // method signature

} public class MyDigitalClock{ public void display(){ // display something ….} …

}

30

Interface implementation

/**  * Line class implements Relation interface  */ public class Line implements Relation {

private double x1; private double x2; private double y1; private double y2; public Line(double x1, double x2, double y1, double y2){

this.x1 = x1; this.x2 = x2; this.y1 = y1; this.y2 = y2;

}

31

Interface implementation

public double getLength(){

double length = Math.sqrt((x2­x1)*(x2­x1) +(y2­y1)* (y2­y1)); return length;

} public boolean isGreater( Object a, Object b){

double aLen = ((Line)a).getLength(); double bLen = ((Line)b).getLength(); return (aLen > bLen);

} public boolean isLess( Object a, Object b){ double aLen = ((Line)a).getLength(); double bLen = ((Line)b).getLength(); return (aLen < bLen);

} public boolean isEqual( Object a, Object b){ double aLen = ((Line)a).getLength(); double bLen = ((Line)b).getLength(); return (aLen == bLen);

}

}

32

Interface Implementation

 When your class tries to implement an interface,  always make sure that you implement all the  methods of that interface.

 A concrete class can only extend one super class,

but it can implement multiple Interfaces

 All abstract methods of all interfaces have to be

implemented by the concrete class

33

Example

public class ComputerScienceStudent extends Student implements PersonInterface, AnotherInterface, Thirdinterface{

// All abstract methods of all interfaces

// need to be implemented. }

34

Cast of reference type

 Substitute the reference of the sub­class for

the reference of the superclass.

public class Animal {

public void cry(){…} } public class Dog extends  Animal{     public void cryDog(){…};

} .. .. Dog taro = new Dog(); Animal obj = taro; obj.cry(); //obj.cryDog(); impossible to call

// Interface Animal public interface Animal {  public void cry(); py(); } public class Dog implements Animal  {  public void cry() {….}  // Implement method of interface  public void cryDog() {….}   // Implement original method  } Dog taro = new Dog(); Animal obj = taro; obj.cry(); // obj.cryDog(); Impossible to call !!  35

Downcasting

 Substitute the reference of the superclass for

the reference of the sub­class

public class Animal {

public void cry(){…} } public class Dog extends  Animal{     public void cryDog(){…};

} .. .. Dog taro = new Dog(); Animal obj = taro; if (obj instanceof Dog){    Dog tempObj= (Dog)obj;    tempObj.cryDog(); //possible to cal }l

36

Polymorphism

 The term polymorphism literally means "having many forms"

 The ability of a reference variable to change behavior

according to what object instance it is holding.

 This allows multiple objects of different subclasses to be

treated as objects of a single super class, while  automatically selecting the proper methods to apply to a  particular object based on the subclass it belongs to.

37

Polymorphism

Object of Dog class

Owh!

cry()

Common Interface cry() Object of Cat class

Mow! cry()

Animal cry() Application program

Object of Mouse class

Chit! cry()

38

Another example

 Given the parent class Person and the

subclass Student, we add another subclass  of Person which is Employee.

 Below is the class hierarchy for that,

Person

Student Employee

39

Example Polymorphism

 Now suppose we have a getName method in our super

class Person, and we override this method in both Student  and Employee subclass's

public class Student {

public String getName(){

System.out.println(“Student Name:” + name);

return name;  }

}

public class Employee {

public String getName(){

System.out.println(“Employee Name:” + name);  return name;

}

}

40

Example Polymorphism

public static main( String[] args ) {

Student studentObject = new Student(); Employee employeeObject = new Employee(); Person ref = studentObject; //Person ref. points to a // Student object // getName() method of Student class is called String temp= ref.getName(); System.out.println( temp ); ref = employeeObject; //Person ref. points to an // Employee object //getName() method of Employee class is called String temp = ref.getName(); System.out.println( temp );

}   when we try to call the getName method of the

reference Person ref, the getName method of the  Student object will be called

41

Example

 In this example, the cry() method of animal class  (Animal) is overridden respectively in dog class  (Dog), cat class (Cat), and mouse class (Mouse).  We will make the objects of the animal, the dog, the  cat, and the mouse class, and store them in the  array of the reference variable of the animal class  that is the superclass. Next, when the ‘cry()’ method  is called for the reference variable of the animal  class, it introduces the example that is executed the  ‘cry()’ method of each class.

42

Polymorphism.java

// Cat class  class Cat extends Animal {

// Animal class class Animal {

public void cry() {

private String name; // Name  public Cat(String name) {

this.name = name; ;

System.out.println("I am an animal. I  don't know how to cry. ");

}

} public void cry() {

System.out.println(“I am a cat” +

} // Dog class class Dog extends Animal {

name + “.Meow !"); }

private String name; // Name  // Constructor public Dog(String name) { this.name = name;

} // Mouse class class Mouse extends Animal {

}

public void cry() {

private String name; // Name  public Mouse(String name) { this.name = name;

System.out.println(“I am a dog” +

name + “. whow !"); }

} public void cry() {

}

System.out.println(“I am a mouse” +  name + “. Chit !");

}

}

43

Polymorphism.java

// Application class Exercise of polymorphism pp py p class Polymorphism {

public static void main(String[] args) { // Object array generation Animal obj[] = {new Animal(), new Dog("Taro"), new Cat(“Tama"), new Mouse(“Kuro") }; // Polymorphism for(int i=0; i

obj[i].cry(); // Cry

}

}

}

44

Abstract method

 Methods that do not have implementation

(body)

 To create an abstract method, just write the

method declaration without the body and use  the abstract keyword  No {  }

 For example,

// Note that there is no body  public abstract void someMethod();

45

Abstract class

 An abstract class is a class that contains one

or more abstract methods

 An abstract class cannot instantiated  Syntax:

public abstract class Class name {

: public abstract Return value type Method name (Argument list) :

}

46

Sample Abstract class

public abstract class LivingThing {

public void breath(){  System.out.println("Living Thing breathing...");

}  public void eat(){

System.out.println("Living Thing eating...");

}  /**    * Abstract method walk()    * We want this method to be implemented by a     * Concrete class.  */  public abstract void walk();  }

47

Extending an abstract class

 When a concrete class extends the LivingThing  abstract class, it must implement the abstract  method walk(), or else, that subclass will also  become an abstract class, and therefore cannot be  instantiated.

public class Human extends LivingThing {

public void walk(){

System.out.println("Human walks...");

}

}

48

When to use Abstract Methods & Abstract Class?

 Abstract methods are usually declared where two or  more subclasses are expected to fulfill a similar role  in different ways through different implementations

 These subclasses extend the same Abstract class and

provide different implementations for the abstract  methods

 Use abstract classes to define broad types of  behaviors at the top of an object­oriented  programming class hierarchy, and use its  subclasses to provide implementation details of the  abstract class.

49

Abstract class vs Interface

 All methods of an Interface are abstract methods  while some methods of an Abstract class are  abstract methods  Abstract methods of abstract class have abstract modifier

 An interface can only define constants while

abstract class can have fields

 Interfaces have no direct inherited relationship with  any particular class, they are defined independently  Interfaces themselves have inheritance relationship

among themselves

50

Example: Abstract class Animal

 In this example the ‘cry()’ method of animal class (Animal) is  defined by the ‘abstract’ method. Therefore, the animal class  is defined as an abstract class. In dog class (Dog), cat class  (Cat), and mouse class (Mouse), the ‘cry()’ method is  overridden respectively. Object of the dog, the cat, and the  mouse class in the array of the reference variable of the  animal class, and calls the ‘cry()’ method

51

Abstract.java

// Cat class  class Cat extends Animal {

private String name; // Name  public Cat(String name) {

// Animal class (abstract class) abstract class Animal { // Cry Method public abstract void cry();

this.name = name; ;

} public void cry() {

} // Dog class class Dog extends Animal {

System.out.println(“I am a cat” +  name +

“.Meow !"); }

private String name; // Name public Dog(String name) { this.name = name;

} // Cry Method (override) public void cry() {

} // Mouse class class Mouse extends Animal {

System.out.println(“I am a dog” +  name + “. Bow­wow !");

private String name; // Name  public Mouse(String name) {

}

this.name = name;

}

} public void cry() {

System.out.println(“I am a mouse” +  name + “. Chit !");

}

}

52

Abstract.java

// Application class Exercise of polymorphism  class Abstract {

public static void main(String[] args) { // Object array generation Animal obj[] = {new Animal(), new Dog("Taro"), new Cat(“Tama"), new Mouse(“Kuro") }; // Polymorphism for(int i=0; i

obj[i].cry(); // Cry

}

}

}

53

Interface example

 In this example we will use interface instead

of abstract class

54

Interface.java

// Cat class  class Cat implements Animal {

private String name; // Name  public Cat(String name) {

// Animal class (abstract class) interface Animal { // Cry Method public abstract void cry();

this.name = name; ;

} public void cry() {

} // Dog class class Dog implements Animal {

System.out.println(“I am a cat” +  name +

“.Meow !"); }

private String name; // Name public Dog(String name) { this.name = name;

} // Cry Method (override) public void cry() {

System.out.println(“I am a dog” +  name + “. Bow­wow !");

} // Mouse class class Mouse implements Animal { private String name; // Name  public Mouse(String name) {

}

this.name = name;

}

} public void cry() {

System.out.println(“I am a mouse” +  name + “. Chit !");

}

}

55

Interface.java

class Interface {

public static void main(String[] args) { // Object array generation Animal obj[] = {new Animal(), new Dog("Taro"), new Cat(“Tama"), new Mouse(“Kuro") }; // Polymorphism for(int i=0; i

obj[i].cry(); // Cry

}

}

}

56

Package

 Set where related classes are grouped together by category.  java.lang— basic language functionality and fundamental types

 java.util— collection data structure classes

 java.io— file operations

 java.math— multiprecision arithmetics

 java.net— networking operations, sockets,

 java.awt— basic hierarchy of packages for native GUI components

 javax.swing— hierarchy of packages for platform­independent rich

GUI components

 java.applet— classes for creating and implementing applets

57

Benefits of Packaging

 You and other programmers can easily determine

that these classes and interfaces are related.  You and other programmers know where to find  classes and interfaces that can provide graphics­ related functions.

 The names of your classes and interfaces won't

conflict with the names in other packages because  the package creates a new namespace.

 You can allow classes  within the package to have  unrestricted access to one another yet still restrict  access for types outside the package.

58

Creating a package

 To create a package, you choose a name for the package  and put a package statement with that name at the top of  every source file that contains the types (classes, interfaces,  enumerations, and annotation types) that you want to  include in the package

package mine.lib; class Account

after compilation

mine directory

lib directory

Account.class

59

Import of package

import packagename.classname; import packagename.*;

// Importing a class import java.util.Date; // Importing all classes in the java.util package import java.util.*;

60

Class path

 It is a set of directories where Java class files  are located Java runtime searches for class  files in the directory specified in the class  path in the order specified

 There are the following two methods for

setting the class path.  Put ‘­classpath’ option to the ‘java’ command and

the ‘javac’ command.

 Set the environment variable ‘CLASSPATH’.

61

Setting the class path

 c:\classes> javac –classpath; c:\classes Sample.java

 You can also set more than one classpath, we just have to  separate them by ;(for windows) and : (for Unix based  systems). For example,

 set classpath=C:\myClasses;D:\;E:\MyPrograms\Java

 C:\schoolClasses> set classpath=C:\

 For Unix base systems, suppose we have our classes in the

directory /usr/local/myClasses, we write,

 export classpath=/usr/local/myClasses

62

Distribution the package

 Use jar command to create an archive file of

package

 jar cvf jarfilename packagename

63

public class

 The class that can be imported between

different packages is called the public. To  define the ‘public’ class, specify the modifier  ‘public’ for the class definition. Only the class  with the modifier public can be imported.

64

static import

 The static import is a function that imports the

static variable and the static method, and  uses it by omitting the class name.

 Syntax

 import static packagename.class name.static variable name;  import static packagename.class name.static method name;  import static packagename.class name;

65

Lab 1

 Give the class Employee of the following

specifications, and a program Management  using its subclass Manager. Please analyze,  and mount subclass Manager from the  execution result of this program  Management.

66

Execution image of program

prompt> java Management ID     :884104 NAME   :Nagatomo SECTION:Education PHONE  :7700­2250 STAFF  :2

67

class Employee

public class Employee { private int id; // ID private String name; // Name  private String section; // Section private String phone; // Extension // Constructor public Employee(int i, String n, String s, String p) {

id = i; name = n; section = s; phone = p;

} // Display method public void print() {

System.out.println("ID     :" + id); System.out.println("NAME   :" + name); System.out.println("SECTION:" + section); System.out.println("PHONE  :" + phone);

}

}

68

class Management

public class Management {

public static void main(String args[]) { Manager mgr = new Manager (884104 "Nagatomo""Education""7700­ 2250" 2);

(884104,  Nagatomo ,   Education ,  7700 2250 , 2);

mgr.print();

}

}

69

Lab 2

 Class ‘ConvertYear’ of the ‘mine.lib’ package is a class with  the function that converts the Christian to the Japanese  calendar. For instance, it converts 2005 of Christian era to  17th of Heisei. The source code of this class has completed,  but it has not been compiled yet. The ‘UsePackage’ class is  incomplete at the application class that uses the  ‘ConvertYear’. Do appropriate processing to these classes,  so that you can obtain the following execution results.

70

Execution image of program

prompt> java UsePackage 2005 2005 is Heisei 17 year, when converting it into

Japanese calendar.

prompt> java UsePackage 1969 1969 is Showa 44 year, when converting it into

Japanese calendar.

prompt> java UsePackage 1907 1907 is Meiji 40 year, when converting it into

Japanese calendar.

71

Directory structure

72

Conversion into value from character  string

 Because all the command line arguments are

handled as the character string, it is  necessary to convert them into the value  when you use them for the calculation. To  convert from the character string into the  integer, do as follows.  String s = ″2001″; // Stringified value  int n = Integer.parseInt(s); // Convert character string into

intege

73

Processing procedure

 a) Compile ‘ConvertYear.java’, and dispose  the class file to the same folder hierarchy as  the package specification.

 b) Mount and compile ‘UsePackage.java’, so  that you can do the same processing as the  execution result.

 c) Start application ‘UsePackage’, and give a

value between 1900 and 2100 from the  command line.

74

ConvertYear.java

package mine.lib;

public class ConvertYear { private final static int MIN_YEAR = 1900;  // Meiji 33 year private final static int MAX YEAR = 2100;  // Heisei 112 year private final static int MEIJI_END = 1911; // Meiji 44 year private final static int TAISHO_END = 1925; // Taisho 14 year private final static int SHOWA_END = 1988; // Showa 63 year

// Conversion method of Japanese calendar

75

// Conversion method of Japanese calendar public String convert(int year) {

String ret = null; if(year>=MIN_YEAR && year<=MAX_YEAR) { // Range check first of all

if(year > SHOWA_END) { // Case of Heisei

int heisei = year ­ SHOWA_END; if(heisei < 10) {

ret = “Heisei0" + heisei + “year";

} else {

ret = “Heisei"  + heisei + “year";

}

} else if (year > TAISHO_END) { // Case of Showa

int showa = year ­ TAISHO_END; if(showa < 10) {

ret = “Showa0" + showa + “year";

} else {

ret = “Showa"  + showa + “year"; y

}

}

76

else if(year > MEIJI_END) { // Case of Taisho int taisho = year ­ MEIJI_END; if(taisho < 10) {

ret = “Taisho0" + taisho + “year";

} else {

ret = “Taisho"  + taisho + “year";

}

} else { // Case of Meiji int meiji = year ­ (1900­33); ret = “Meiji"  + meiji + “year";

} } else {

ret = "Outside of the scope"; ret =  Outside of the scope ;

} return ret; } }

77