BMICALCULATOR

표준체중계산기 (BMI Calculator)
-label, button, radiobutton, textfield

– 표준체중
// 남자표준체중 = 신장(m) x 신장(m) x 22
// 여자표준체중 = 신장(m) x 신장(m) x 21

– BMI
// BMI = 체중(kg)/신장^2(m^2)
// 20 미만 저체중 (Underweight)
// 20~24 정상 (Normal)
// 25~29 과체중 (Overweight)
// 30 이상 비만 (Obesity)

– 하루 권장 섭취량 
// 한국인 하루권장섭취량 남성 2600 kcal 여성 2100 kcal
// 기초대사량산출공식 (Herris Benedict Equation)
// 기초대사량(남성) = 66.47 + (13.75*weight) + (5*height) – (6.76*age)
// 기초대사량(여성) = 655.1 + (9.05*weight) + (1.85*height) – (4.68*age)
// 활동대사량 = 저활동적(1.3)/중간활동적(1.5)/활동적(1.75)
// 개인별 하루권장섭취량(kcal) = 기초대사량 * 활동대사량

 

enum BMI {
UNDERWEIGHT, NORMAL, OVERWEIGHT, OBESITY
}

enum Gender {
FEMALE, MALE
}

enum Activity {
LOW, MEDIUM, HIGH;

public static String[] names() {
String[] names = new String[Activity.values().length];
for (Activity t : Activity.values())
names[t.ordinal()] = t.toString();
return names;
}

public static Activity valueOf(int value)
{
switch(value) {
case 0:
return LOW;
case 1:
return MEDIUM;
case 2:
return HIGH;
default:
return null;
}
}
}

public class BMICalculator {

public int age = 20;
public double height = 165;
public double weight = 55;
public Gender gender = Gender.FEMALE;
public Activity activity = Activity.MEDIUM;

public BMICalculator()
{
this(20, 165.0, 55.0, Gender.FEMALE, Activity.MEDIUM);
}

public BMICalculator(int age, double height, double weight, Gender gender, Activity activity)
{
this.age = age;
this.height = height;
this.weight = weight;
this.gender = gender;
this.activity = activity;
}

public BMI calculateBMI()
{
double bmi = weight / (height * 0.01) / (height * 0.01);
if (bmi >= 0.0 && bmi < 20.0)
{
return BMI.UNDERWEIGHT;
}
else if (bmi >= 20.0 && bmi < 24.0)
{
return BMI.NORMAL;
}
else if (bmi >= 24.0 && bmi < 30.0)
{
return BMI.OVERWEIGHT;
}
else
{
return BMI.OBESITY;
}
}

public double calculateStandardWeight()
{
if (this.gender == Gender.MALE) {
return height * height * 22 * 0.0001;
}
return height * height * 21 * 0.0001;
}

// Herris Benedict Equation
public double calculateDailyCaloryIntake()
{
double activityCalory = 1.0;
switch (this.activity)
{
case LOW:
activityCalory = 1.3;
case MEDIUM:
activityCalory = 1.5;
case HIGH:
activityCalory = 1.75;
}

if (this.gender == Gender.MALE) {
return 66.47 + (13.75 * this.weight) + (5.0 * this.height) – (6.76 * (double)(this.age)) * activityCalory;
}
return 655.1 + (9.05 * this.weight) + (1.85 * this.height) – (4.68 * (double)(this.age)) * activityCalory;
}
}

/////////////////////////////////////////////////////////////////////////////

 

JLabel label1 = new JLabel(“나이”); // 레이블 초기화
JLabel label2 = new JLabel(“키(cm)”); // 레이블 초기화
JLabel label3 = new JLabel(“몸무게(kg)”); // 레이블 초기화
JLabel label4 = new JLabel(“성별”); // 레이블 초기화
JLabel label5 = new JLabel(“활동량”); // 레이블 초기화
JTextField textfield1 = new JTextField(10); // age 텍스트필드 초기화
JTextField textfield2 = new JTextField(10); // height 텍스트필드 초기화
JTextField textfield3 = new JTextField(10); // weight 텍스트필드 초기화
JRadioButton rbutton1 = new JRadioButton(“여자”, true); // gender 라디오버튼
JRadioButton rbutton2 = new JRadioButton(“남자”); // gender 라디오버튼
String[] names = {“Low”, “Medium”, “High”};
JComboBox<String> combobox1 = new JComboBox<String>(names); // acitivity 콤보박스

JButton button1 = new JButton(“계산”); // bmi calculator 버튼 초기화

JLabel label6 = new JLabel(“BMI 지수”); // 레이블 초기화
JLabel label7 = new JLabel(“정상 몸무게”); // 레이블 초기화
JLabel label8 = new JLabel(“일일 칼로리섭취량”); // 레이블 초기화
JTextField textfield4 = new JTextField(10); // bmi 텍스트필드 초기화
JTextField textfield5 = new JTextField(10); // standard weight 텍스트필드 초기화
JTextField textfield6 = new JTextField(10); // dailry calory intake 텍스트필드 초기화

JPanel panel = new JPanel(); // 패널 초기화
JPanel panel1 = new JPanel(new GridLayout(0, 2)); // 패널 초기화
JPanel panel2 = new JPanel(new GridLayout(0, 2)); // 패널 초기화
JPanel panel3 = new JPanel(new GridLayout(0, 2)); // 패널 초기화
JPanel panel4 = new JPanel(new GridLayout(0, 2)); // 패널 초기화
JPanel panel5 = new JPanel(); // 패널 초기화
JPanel panel6 = new JPanel(new GridLayout(0, 2)); // 패널 초기화
JPanel panel7 = new JPanel(); // 패널 초기화
JPanel panel8 = new JPanel(new GridLayout(0, 2)); // 패널 초기화
JPanel panel9 = new JPanel(new GridLayout(0, 2)); // 패널 초기화
JPanel panel10 = new JPanel(new GridLayout(0, 2)); // 패널 초기화

 

public BMICalculatorFrame() {
super(“BMICalculatorFrame”);

// frame
panel1.add(label1);
panel1.add(textfield1);

panel2.add(label2);
panel2.add(textfield2);

panel3.add(label3);
panel3.add(textfield3);

panel5.add(rbutton1);
panel5.add(rbutton2);
panel4.add(label4);
panel4.add(panel5);

panel6.add(label5);
panel6.add(combobox1);

panel7.add(button1);

panel8.add(label6);
panel8.add(textfield4);

panel9.add(label7);
panel9.add(textfield5);

panel10.add(label8);
panel10.add(textfield6);

panel.add(panel1);
panel.add(panel2);
panel.add(panel3);
panel.add(panel4);
panel.add(panel6);
panel.add(panel7);
panel.add(panel8);
panel.add(panel9);
panel.add(panel10);
add(panel);

// event
textfield1.addKeyListener(this);
textfield2.addKeyListener(this);
textfield3.addKeyListener(this);
button1.addActionListener(this);

setSize(350, 300);
setResizable(false);
setVisible(true);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

ARIDITY INDEX

건조지수(Aridity Index)를 구하고, 기후의 상태를 알려주는 프로그램을 작성한다

(1) 사용자에게 연강수량(Precipitation)과 연평균기온(Temperature)를 입력 받는다. 연강수량의 단위는 mm이고, 연평균기온의 단위는 oC이다.

(2) 건조지수를 다음 공식으로 계산하고 결과를 화면에 출력한다.
건조지수 De Martonne Aridity Index = Precipitation/ (Temperature + 10)

(3) 다음 기준에 따라 기후의 상태를 판단해서 화면에 출력한다.
AI >= 60 => Perhumid
30 <= AI < 60 => Humid
20 <= AI < 30 => SubHumid
15 <= AI < 20 => SemiArid
5 <= AI < 15 => Arid
AI < 5 => ExtremelyArid

 

///////////////////////////////////

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

//File: AridityIndexCalculator.java
//Class: AridityIndexCalculator
//Kyoung Shin Park (2016 Fall)

public class AridityIndexFrame extends JFrame implements ActionListener, KeyListener {

JLabel label1 = new JLabel(“연평균 온도 (C)”); // 레이블 초기화
JLabel label2 = new JLabel(“강수량 (mm)”); // 레이블 초기화
JLabel label3 = new JLabel(“건조지수 (LA)”); // 레이블 초기화

JTextField textfield1 = new JTextField(20); // 텍스트필드 초기화
JTextField textfield2 = new JTextField(20); // 텍스트필드 초기화
JTextField textfield3 = new JTextField(20); // 텍스트필드 초기화

JButton button1 = new JButton(“확인”); // 버튼 초기화

JPanel panel = new JPanel(); // 패널 초기화
JPanel panel1 = new JPanel(); // 패널 초기화
JPanel panel2 = new JPanel(); // 패널 초기화
JPanel panel3 = new JPanel(); // 패널 초기화

public AridityIndexFrame() {
super(“Aridity Index Frame”);

// frame
panel1.add(label1);
panel1.add(textfield1);

panel2.add(label2);
panel2.add(textfield2);

panel3.add(label3);
panel3.add(textfield3);

panel.add(panel1);
panel.add(panel2);
panel.add(panel3);
panel.add(button1);
add(panel);

// event
textfield1.addKeyListener(this);
textfield2.addKeyListener(this);
button1.addActionListener(this);

setSize(350, 200);
setResizable(false);
setVisible(true);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

private double ToDouble(String str)
{
return Double.parseDouble(str);
}

public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
if (button == button1) {
this.dispose();
}
}

public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_ENTER) {
Toolkit.getDefaultToolkit().beep();
System.out.println(“ENTER pressed”);
JTextField textfield = (JTextField) e.getSource();
double T = ToDouble(textfield1.getText());
double P = ToDouble(textfield2.getText());
textfield3.setText(“” + AridityIndexCalculator.Martonne(T, P));
}
}

public static void main(String[] args) {
new AridityIndexFrame();
}
}

GeometryType

import java.util.*;

public enum GeometryType {
NONE(0),
SPHERE(1),
CONE(2),
CYLINDER(3),
RECTANGULAR_PRISM(4),
SQUARE_PYRAMID(5),
ISOSCELES_TRIANGULAR_PRISM(6);

private int type;

private GeometryType(int type) {
this.type = type;
}

public int getType() {
return type;
}

public static GeometryType valueOf(int value) {
switch(value) {
case 1:
return SPHERE;
case 2:
return CONE;
case 3:
return CYLINDER;
case 4:
return RECTANGULAR_PRISM;
case 5:
return SQUARE_PYRAMID;
case 6:
return ISOSCELES_TRIANGULAR_PRISM;
default:
return null;
}
}

public static GeometryType nameOf(String name) {
if (name.contentEquals(“SPHERE”) || name.contentEquals(“Sphere”))
return SPHERE;
else if (name.contentEquals(“CONE”) || name.contentEquals(“Cone”))
return CONE;
else if (name.contentEquals(“CYLINDER”) || name.contentEquals(“Cylinder”))
return CYLINDER;
else if (name.contentEquals(“RECTANGULAR_PRISM”) || name.contentEquals(“RectangularPrism”))
return RECTANGULAR_PRISM;
else if (name.contentEquals(“SQUARE_PYRAMID”) || name.contentEquals(“SquarePyramid”))
return SQUARE_PYRAMID;
else if (name.contentEquals(“ISOSCELES_TRIANGULAR_PRISM”) || name.contentEquals(“IsoscelesTriangularPrism”))
return ISOSCELES_TRIANGULAR_PRISM;
else
return null;
}

public static String[] names() {
String[] names = new String[GeometryType.values().length];
for (GeometryType t : GeometryType.values())
names[t.ordinal()] = t.toString();
return names;
}
}

HW2 Utility.java

import java.util.Scanner;

public class Utility {
// get user input double
public static double getUserInputDouble() {
double value;
Scanner scan = new Scanner(System.in);
while(true) {
try {
value = scan.nextDouble();
break;
}
catch (Exception e) {
System.out.print(“Error! Please re-enter [double value]: “);
scan.next();
}
}
return value;
}

// get between min_value and max_value
public static int getUserInputBetween(int min, int max)
{
int value = 0;
Scanner scan = new Scanner(System.in);
do {
System.out.printf(“Please enter the value %d-%d.\n”, min, max);
try {
value = scan.nextInt();
} catch (Exception e) {
System.out.printf(“ERROR! Valid range %d-%d. Please re-enter!\n”, min, max);
scan.next();
continue;
}
} while (value < min || value > max);
return value;
}

// get user input ‘q’-key
public static boolean getUserExitKey()
{
System.out.println(“Press q-key to exit the program or enter-key to start the program”);
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
if (s.contentEquals(“q”)) {
return true;
}
else {
return false;
}
}

public static FigureType getUserFigure()
{
FigureType type = null;
Scanner scan = new Scanner(System.in);
do {
System.out.println(“Please select Figure [TRIANGLE, SQUARE, RECTANGLE, PARALLELOGRAM, RHOMBUS, TRAPEZOID]”);
try {
String inputString = scan.nextLine();
type = FigureType.nameOf(inputString);
if (type != null) return type;
} catch (Exception e) {
System.out.println(“ERROR! Please re-enter!”);
scan.next();
}
} while (type == null);
return type;
}

public static GeometryType getUserGeometry()
{
GeometryType type = null;
Scanner scan = new Scanner(System.in);
do {
System.out.println(“Please select geometry [SPHERE, CONE, CYLINDER, RECTANGULAR_PRISM, SQUARE_PYRAMID, ISOSCELES_TRIANGULAR_PRISM]:”);
try {
String inputString = scan.nextLine();
type = GeometryType.nameOf(inputString);
if (type != null) return type;
} catch (Exception e) {
System.out.println(“ERROR! Please re-enter!”);
scan.next();
}
} while (type == null);
return type;
}
}

Person & Student Class

// Person

class Person
{
private static int count = 0; // static (class) variables
protected String name; // instance variables
protected int age; // instance variables
public Person() { // default constructor
this(“”, 0);
}
public Person(String name, int age) {
count++;
this.name = name;
this.age = age;
}
public String getName(){
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void set(String name, int age){
this.name = name;
this.age = age;
}
public void set(Person other){
this.set(other.name, other.age);
}
public Person clone(){
return new Person(this.name, this.age);
}
public String toString() { // Object.toString() overriding
return “Person Name: ” + name + ” Age: ” + age;
}
public void print() { // instance method & virtual method
System.out.println(“Person Name: ” + name + ” Age: ” + age);
}
public static void printCount(){ // static (class) methods
System.out.println(“Person Count: ” + count);
}
public static int getCount() { return count; } // static (class) methods
public static void setCount(int value) { count = value; } // static (class) methods
}

// Student

class Student extends Person
{
private static int count = 0; // static (class) variables
protected int id;
public Student() {
id = 5208;
}
public Student(String name, int age, int id) {
super(name, age);
this.id = id;
count++;
}
public int getID() {
return id;
}
public void setID(int id) {
this.id = id;
}
public void set(String name, int age, int id){
super.set(name, age);
this.id = id;
}
public void set(String name, int age){
super.set(name, age);
}
public void set(Student other){
this.set(other.name, other.age, other.id);
}
public void set(Person other){
if (other instanceof Student)
this.set((Student)other);
else
super.set(other);
}
public Student clone(){
return new Student(this.name, this.age, this.id);
}
public String toString() { // Object.toString() overriding
return “Student Name: ” + name + ” Age: ” + age + ” ID: ” + id;
}
public void print() { // Person class print() method overriding
System.out.println(“Student Name: ” + name + ” Age: ” + age + ” ID: ” + id);
}
public void superPrint() {
super.print();
}
public static void printCount() { // static (class) methods
System.out.println(“Student Count: ” + count);
}
public static int getCount() { return count; } // static (class) methods
public static void setCount(int value) { count = value; } // static (class) methods
}

// PersonStudentTest

class PersonStudentTest
{
static void print(Object o) {
System.out.println(o);
}
static void print(Person[] arr) {
for (Person p : arr)
System.out.println(p);
}
public static void main(String[] args)
{
Person h1 = new Person(“JAVA”, 2016);
h1.print();
print(h1);
System.out.println(h1);

Person h2 = new Student(); // 기본생성자를 불렀을때 자기 count를 증가시키지 않는다
//h2.print();
// print(h2);
//System.out.println(h2);

Object o = h2; // upcasting
print(o); // dynamic binding
((Student)o).print();
((Person)o).print(); // o=> Person type => Person.print() => dynamic binding Student.print()

Person.printCount(); // calls Person printCount()
Student.printCount(); // calls Student printCount()
System.out.println();
}
}

// PersonStudentTest

class PersonStudentTest
{
static void print(Object o) {
System.out.println(o);
}
static void print(Person[] arr) {
for (Person p : arr)
System.out.println(p);
}
public static void main(String[] args)
{
Person h1 = new Person(“JAVA”, 2016);
h1.print();
print(h1);
System.out.println(h1);

Person h2 = new Student(); // 기본생성자를 불렀을때 자기 count를 증가시키지 않는다
//h2.print();
// print(h2);
//System.out.println(h2);

Object o = h2; // upcasting
print(o); // dynamic binding
((Student)o).print();
((Person)o).print(); // o=> Person type => Person.print() => dynamic binding Student.print()

Person.printCount(); // calls Person printCount()
Student.printCount(); // calls Student printCount()
System.out.println();

Person[] pList = new Person[5];
pList[0] = new Person(“JAVA1”, 1);
pList[0].print();
pList[1] = pList[0];
pList[1].print();
pList[2] = new Student(); // default constructor count증가 안함
pList[2].print();
pList[3] = new Student(“JAVA2”, 2, 222); // Student.count++
pList[3].print();
pList[4] = pList[3];
pList[4].print();

System.out.println(“AFTER SET”);
pList[0].set(“JAVA3”, 3); // Person.set(string, int)
pList[4].set(“JAVA4”, 4); // Person.set(string, int)
print(pList);

System.out.println(“AFTER SET2”);
Student s = (Student)pList[4]; // down casting
s.set(“JAVA5”, 5, 555); // Student.set(string, int, int)
print(pList);

System.out.println(“AFTER SET3”);
pList[0].set(pList[4]); // Person.set(Person)
print(pList);

System.out.println(“AFTER SET4”);
((Student)pList[2]).set(pList[4]); // Student.set(Person)
//((Student)pList[2]).set((Student)pList[4]); // Student.set(Student)
print(pList);

System.out.println(“AFTER SET5”);
((Student)pList[2]).set(new Person(“JAVA6”, 6)); // Student.set(Person)
//((Student)pList[2]).set((Student)pList[4]); // Student.set(Student)
print(pList);

Person.printCount(); // calls Person printCount()
Student.printCount(); // calls Student printCount()
System.out.println();
}
}

 

Java swap pass-by-value

static void swap(int p, int q) // Java uses pass-by-value
{
int t = p;
p = q;
q = t;
}

static void swap2(int[] p, int[] q)  // Java uses pass-by-value
{
int t = p[0];
p[0] = q[0];
q[0] = t;
}

static void swap(int[] p, int[] q)  // Java uses pass-by-value
{
int[] t = p;
p = q;
q = t;
}

static void swap2(int[][] p, int[][] q)  // Java uses pass-by-value
{
int[] t = p[0];
p[0] = q[0];
q[0] = t;
}

static void swap(Point p, Point q)        // Java uses pass-by-value
{
Point t = p;
p = q;
q = t;
}

static void swap2(Point p, Point q)        // Java uses pass-by-value
{
double[] t = p.get(); // T t = p
p.set(q.get());  // p = q
q.set(t);  // q = t
}

////////////////////////////////////////

public static void main(String[] args)
{
Point p1 = new Point(10.5, 10.7);
Point p2 = new Point(1.5, 1.7);

swap(p1, p2);
System.out.println(“After swap p1=” + p1 + ” p2 ” + p2); // p1=(10.5, 10.7) p2=(1.5, 1.7)
swap2(p1, p2);
System.out.println(“After swap2 p1=” + p1 + ” p2 ” + p2); // p1=(1.5, 1.7) p2=(10.5, 10.7)

int[] arr1 = { 1, 2, 3 };
int[] arr2 = { 4, 5, 6, 7, 8 };
swap(arr1, arr2);
System.out.print(“arr1: “);
System.out.println(Arrays.toString(arr1)); // arr1: [1, 2, 3]
System.out.print(“arr2: “);
System.out.println(Arrays.toString(arr2)); // arr2: [4, 5, 6, 7, 8]

int[][] array1 = { new int[] { 1, 2, 3 } };
int[][] array2 = { new int[] { 4, 5, 6, 7, 8 } };
swap2(array1, array2);
System.out.print(“array1: “);
System.out.println(Arrays.toString(array1[0])); // array1: [4, 5, 6, 7, 8]
System.out.print(“array2: “);
System.out.println(Arrays.toString(array2[0])); // array2: [1, 2, 3]

int a = 10;
int b = 20;
swap(a, b);
System.out.println(“a=” + a); // a=10
System.out.println(“b=” + b); // b=20

int[] a2 = { 10 };
int[] b2 = { 20 };
swap2(a2, b2);
System.out.println(“a2=” + a2[0]); // a2 = 20
System.out.println(“b2=” + b2[0]); // b2 = 10
}

 

Instance vs Static Method Overriding

PersonStudentClass

/// Person

class Person
{
static int count = 0; // static (class) variables

String name; // instance variables
int age; // instance variables

public Person()
{
//System.out.println(“Person Constructor”); // this(“”, 0); error: call to this must be first statemenht in constructor
this(“”, 0);
}

public Person(String name, int age)
{
count++;
this.name = name;
this.age = age;
}

public static void printCount() // static (class) method
{
System.out.println(“Person Count: ” + count);
}

public static int getCount() { return count; } // static (class) methods

 

public String toString() // Object.toString() overriding
{
return “Person Name: ” + name + ” Age: ” + age;
}

public void print() // instance methods
{
System.out.println(“Person Name: ” + name + ” Age: ” + age);
}
}

/// Student

class Student extends Person
{
static int scount = 0; // static (class) variables
int id;

public Student()
{
this(“”, 0, 5208);
}

public Student(String name, int age, int id)
{
super(name, age);
this.id = id;
scount++;
}

public static void printCount() // static (class) method overriding
{
System.out.println(“Student Count: ” + scount);
}

public String toString() // Object.toString() overriding
{
return “Student Name: ” + name + ” Age: ” + age + ” ID: ” + id;
}

public void print() // Person class print() method overriding
{
System.out.println(“Student Name: ” + name + ” Age: ” + age + ” ID: ” + id);
}

}

 

class PersonStudentTest
{
public static void main(String[] args)
{
Person p1 = new Student(“Kyoung”, 22, 1207);
p1.print(); // dynamic binding Student Name: Kyoung Age: 22 ID: 1207
p1.name = “JAVA”; // default (package private)
p1.age = 1; // default (package private)
//p1.id = 2016; // default (package private) cannnot call id coz Person System.out.println(p1); // dynamic binding Student Name: JAVA Age: 1 ID: 1207
p1.printCount(); // calls Person p1 printCount() 1
Person.printCount(); // calls Person printCount() 1
Student.printCount(); // calls Student printCount() 1
System.out.println();

Student s1 = (Student)p1;
s1.name = “JAVA”; // default (package private)
s1.age = 2; // default (package private)
s1.id = 2016; // default (package private)
s1.print(); // Student Name: JAVA Age: 2 ID: 2016
s1.printCount(); // calls Student s1 printCount() 1
Person.printCount(); // calls Person printCount() 1
Student.printCount(); // calls Student printCount() 1
System.out.println();

Student s2 = new Student(“Shin”, 20, 1207);
s2.print(); // Student Name: Shin Age: 20 ID: 1217
s2.printCount(); // calls Student s2 printCount() 2
Person.printCount(); // calls Person printCount() 2
Student.printCount(); // calls Student printCount() 2
System.out.println();

Person p2 = new Person(“Park”, 10);
p2.printCount(); // calls Person p2 printCount() 3
Person.printCount(); // calls Person printCount() 3
Student.printCount(); // calls Student printCount() 2
System.out.println();

Person p3 = new Person();
p3.printCount(); // calls Person p3 printCount() 4
Person.printCount(); // calls Person printCount() 4
Student.printCount(); // calls Student printCount() 2
System.out.println();

System.out.println(“Number of Person: ” + Person.getCount()); // 4
}
}

 

Method Overloading vs Overriding

http://www.programmerinterview.com/index.php/java-questions/method-overriding-vs-overloading/

Method Overloading: 동일한 함수명에 매개변수가 다른 함수를 둘 이상 정의하는 것으로, 동일한 함수 기능을 수행하지만 다른 매개변수의 경우를 처리할 때 사용
//compiler error – can’t overload based on the 
//type returned (one method returns int, the other returns a float):
//int changeDate(int Year) ;
//float changeDate (int Year);

//compiler error – can’t overload by changing just
//the name of the parameter (from Year to Month):
//int changeDate(int Year);
//int changeDate(int Month) ;

//valid case of overloading,
//since the methods have different number of parameters:
int changeDate(int Year, int Month) ;
int changeDate(int Year);

//also a valid case of overloading,
//since the parameters are of different types:
int changeDate(float Year) ;
int changeDate(int Year);

Method Overriding: 상속받은 파생 클래스에서 동일한 함수명에 동일한 매개변수로 정의하여 함수를 재정의하는 것으로 상속되어진 함수의 기능을 변경해서 재사용하고 싶을 때 사용

public class Parent {

public int someMethod() {

return 3;

}
}

public class Child extends Parent{

// this is method overriding:
public int someMethod() {

return 4;

}

}

protected constructor

protected constructor는 추상클래스 (abstract class)에서 사용을 권고함. 추상 클래스를 상속받는 파생클래스에서 파생 클래스 생성자가 부모 클래스 즉, 추상 클래스를 초기화 하기 위해 추상 클래스 생성자를 호출 할 수 있도록 지원함.
public abstract class Shape
{

protected Shape(String name) { this.name = name; }
private String name;
public void print() { System.out.print(this.name); }
}
public class Triangle extends Shape
{
private double bottom, height;

public Triangle(String name) { super(name); this.bottom = 1; this.height = 1; }

public void print()
{
super.print();
System.out.printf(” 밑변: %f 높이: %f\n”, this.bottom, this.height);
}
}
public class Rectangle extends Shape
{
private double width, height;

public Rectangle(String name) { super(name); this.width = 2; this.height = 3; }

public void print()
{
super.print();
System.out.printf(” 가로: %f 세로: %f\n”, this.width, this.height);
}
}
class ShapeTest
{
public static void main(String[] args)
{
// Shape s = new Shape(“도형”); // Error; Shape is abstract; cannot be instantiated
Shape s = new Triangle(“삼각형”);
s.print(); // 삼각형 밑변: 1 높이: 1
s = new Rectangle(“직사각형”);
s.print(); // 직사각형 가로: 2 세로: 3
}
}