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();
}
}

 

Car Sedan Class

public class Car  {

// member field
private boolean disel; // private은 파생 클래스에서 사용하지 못함
protected boolean gasoline; // protected은 파생 클래스에서 사용 가능하나 외부(다른 패키지)에서는 호출하지 못함
protected int wheel = 4;

// constructor
protected Car() { disel = true; gasoline = true; }
protected Car(int wheel) { this.wheel = wheel; disel = false; gasoline = false; }

// method
protected void Move()
{
if (disel)
System.out.println(“Disel Car”);
System.out.println(“Move wheel=” + wheel);
}

}

public class Sedan extends Car  {

// member field
private boolean gasoline; // 파생 클래스에서 기반클래스에 멤버필드명이 같다면 default는 자신의 멤버부터 호출 & 
this.gasoline을 사용함 

// constructor
public Sedan() { gasoline = false; } // 내부적으로 super() 호출
public Sedan(int wheel)  { super(wheel); gasoline = true; } //
super(int wheel)를 호출 – protected 생성자는 파생클래스에서 호출 가능

// method
public void sedanMove()
{

// base의 gasoline과 this의 gasoline을 구분해야하는 경우
if (super.gasoline)
System.out.print(“Gasoline Car “);
if (this.gasoline)
System.out.print(“Gasoline SedanCar “);

System.out.println(“move wheel=” + wheel);

}

static void Main(string[] args)
{

Car myCar = new Car(); // protected 생성자 같은 패키지 내에 사용가능.
myCar.move(); // protected 메소드 호출 가능
System.out.println(“myCar wheel=” +  myCar.wheel); // protected 필드 호출 가능

// 바퀴 4개 디젤 자동차
Sedan myCar1 = new Sedan(); // public 생성자 호출 가능
myCar1.move(); // protected 메소드 호출 가능
myCar1.sedanMove(); // public 메소드 호출가능

 

// 바퀴 6개 가솔린 자동차
Sedan myCar2 = new Sedan(6); // public 생성자 호출 가능
myCar2.move(); // protected 메소드 호출 가능
myCar2.sedanMove(); // public 메소드 호출가능

}

}

BankAccount Class

class BankAccount
{

double balance; // instance field
string name; // instace field
static double interest; // static field

public BankAccount() // default constructor
{

this(1000, “JAVA17”) ;
}

public BankAccount(double balance, string name)
{

this.balance = balance;
this.name = name;
BankAccount.interest = 0.7; // 0.7%

}

public void deposit(double amount) // instance method
{

balance += amount;

}

public void withdrawal(double amount) // instance method
{

balance -= amount;

}

public void print() // instance method
{

double currentBalance = balance + balance * interest * 0.01;

System.out.printf(“%s의 계좌 잔고는 %f\n”, name, currentBalance);

}

public static void setInterestRate(double interest) // static method
{

BankAccount.interest = interest;

}

}

 

class BankAccountTest {

public static void main(String[] args) {

BankAccount b = new BankAccount(5000, “HCI222222222222”);
b.print();

b.deposit(1000);
b.print();

b.withdrawal(500);
b.print();

BankAccount.setInterestRate(1.5); // 1.5%
b.print();

BankAccount b2 = new BankAccount();
b2.print();

}

}

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
}

 

Java Parameter Passing: Pass-by-value only

//pass value type by value (값형식을 값에 의한 전달) – copy of value 전달

static void square1(int x) {
x *= x;
System.out.printf(“The value inside square1: %d\n”, x);
}
public static void main(String[] args)
{
int i = 5;
System.out.println(“Before i=” + i);
square1(i);
System.out.println(“After i=” + i + “\n\n”);
}
//Before i=5
//The value inside square1: 25
//After i=5

//pass reference type by value (참조형식을 값에 의한 전달) – copy of reference 전달

static void square2(IntValue value) {
value.x *= value.x;
System.out.printf(“The value inside square2: %d\n”, value.x);
}
public static void main(String[] args)
{
int i = 5;
IntValue value = new IntValue(i);
System.out.println(“Before value.x=” +value.xi);
square2(value);
System.out.println(“After value.x=” + value.x + “\n\n”);
}
//Before value.x=5
//The value inside square2: 25
//After value.x=25
//pass reference type by value (참조형식을 값에 의한 전달) – copy of reference 전달

static void changeArray1(int[] arr)
{

arr[0]=888; // arr -> myArray이므로 원본 배열의 첫번째 값은 888로 변경
System.out.println(“changeArray1 arr=” + Arrays.stream(arr).mapToObj(String::valueOf).collect(Collectors.joining(“,”)));
arr = new int[] {-3, -1, -2, -3, -4}; // local 변수로 새롭게 할당하여 지정 그러나 원본 배열 변경 안됨
System.out.println(“changeArray1 arr=” + Arrays.stream(arr).mapToObj(String::valueOf).collect(Collectors.joining(“,”)));
}
 
public static void main(String[] args)
{
int[] myArray = {1, 4, 5};
System.out.println(“Before myArray=” + Arrays.stream(myArray).mapToObj(String::valueOf).collect(Collectors.joining(“,”)));
changeArray1(myArray);
System.out.println(“After changeArray1 myArray=” + Arrays.stream(myArray).mapToObj(String::valueOf).collect(Collectors.joining(“,”)));
}
//Before myArray=1, 4, 5
//changeArray1 arr=888, 4, 5
//changeArray1 arr=-3, -1, -2, -3, -4
//After myArray=888, 4, 5

 

//pass reference type by value (참조형식을 값에 의한 전달) – copy of reference 전달

 

static void changeArray2(IntValue[] arr)
{
arr[0].x=888; // 원본 배열의 첫번째 값은 888로 변경
System.out.println(“changeArray2 arr=” + Arrays.stream(arr).map(Object::toString).collect(Collectors.joining(“,”)));
arr = new IntValue[] { new IntValue(-3), new IntValue(-1), new IntValue(-2), new IntValue(-3), new IntValue(-4)};  // local 변수로 새롭게 할당하여 지정 그러나 원본 배열 변경 안됨
System.out.println(“changeArray2 arr=” + Arrays.stream(arr).map(Object::toString).collect(Collectors.joining(“,”)));
}
public static void main(String[] args)
{
IntValue[] myArray2 = { new IntValue(1), new IntValue(4), new IntValue(5)};
System.out.println(“Before myArray2=” + Arrays.stream(myArray2).map(Object::toString).collect(Collectors.joining(“,”)));
changeArray2(myArray2);
System.out.println(“After myArray2=” + Arrays.stream(myArray2).map(Object::toString).collect(Collectors.joining(“,”)));
}
// Before myArray2=1, 4, 5
// changeArray2 arr=888, 4, 5
// changeArray2 arr=-3, -1, -2, -3, -4
// After myArray2=888,-4,5

 

 

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 statement 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;

}

}

Person Array

PersonTest-InstanceStatic

instance member field & method vs static member field & method 이해

public class Person {
String name; // instance member field
int age;
public Person() { // default constructor
this(“JAVA17”, 2017); // call Person(String n, int a);
}
public Person(String name, int age) { // constructor
this.name = name;
this.age = age;
}
public void setName(String name) { // instance method
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void print() {
System.out.println(“Person Name=” + name + ” Age=” + age);
}
@Override
public String toString() {
return “Person Name=” + name + ” Age=” + age;
}
}

public class Person2 {
static String name; // static member field
static int age; // static member field
public Person2() { // default constructor
this(“JAVA17”, 2017); // call Person2(String n, int a);
}
public Person2(String n, int a) { // constructor
name = n;
age = a;
}
public static void setName(String n) { // static method
name = n;
}
public static void setAge(int a) { // static method
age = a;
}
public static String getName() { // static method
return name;
}
public static int getAge() { // static method
return age;
}
public static void print() { // static method에서는 this 사용 불가
System.out.println(“Person Name=” + name + ” Age=” + age);
}
@Override
public String toString() {
return “Person Name=” + this.name + ” Age=” + this.age; // instance method에서는 static member variable 접근 가능
}
}

 

public class Person3 {
static String name; // static member field
static int age; // static member field
private Person3() { // default constructor
}
public static void setName(String n) { // static method
name = n;
}
public static void setAge(int a) { // static method
age = a;
}
public static String getName() { // static method
return name;
}
public static int getAge() { // static method
return age;
}
public static void print() { // static method에서는 this 사용 불가
System.out.println(“Person Name=” + name + ” Age=” + age);
}
}

 

public class PersonTest {
static Scanner input = new Scanner(System.in);

public static void main(String[] args) {
Person[] pArray = new Person[3];

// 만약 Person 객체를 하나만 생성한 후 for문에서 공유해 사용할 경우
// 마지막으로 입력된 데이터로 모든 데이터값이 치환됨
Person p = new Person();
for (int i = 0; i < 3; i++) {
System.out.print(“\n\nEnter Person name and age : “);
p.setName(input.next()); // 입력정보
p.setAge(input.nextInt()); // 입력정보
p.Print();
pArray[i] = p; //배열에 들어간 모든 원소는 동일한 p
}

System.out.println(“pArray : ” + Arrays.toString(pArray));

Person[] pArray2 = new Person[3];
// 아래와 같이 for문 안에 Person p = new Person()와같이
// 새로운 객체를 생성해야 각자 다르게 입력된 정보가 들어가게 됨
for (int i = 0; i < 3; i++) {

Person p2 = new Person();

System.out.print(“\n\nEnter Person name and age : “);
p2.setName(input.next()); // 입력정보
p2.setAge(input.nextInt()); // 입력정보
p2.Print();

pArray2[i] = p2; // p2는 새로운 Person객체이므로 배열에서 각각 다른 원소가 들어간다

}

System.out.println(“pArray2 : ” + Arrays.toString(pArray2));

 

Person2[] pArray3 = new Person2[3];
// 만약 Person2 객체의 name과 age는 static으로 사용할 경우
// static은 공유하는 것이므로, 마지막으로 입력된 데이터로 모든 데이터값이 치환됨
for (int i = 0; i < 3; i++) {

Person2 p3 = new Person2();

System.out.print(“\n\nEnter Person name and age : “);
p3.setName(input.next()); // Person2.setName(input.next())와 동일
p3.setAge(input.nextInt()); // Person2.setAge(input.nextInt())와 동일

pArray3[i] = p3; // p3 객체의 name과 age는 static이므로 모두 공유하기때문에, 배열의 모든 원소는 마지막에 들어간 정보로 셋팅

}

System.out.println(“pArray3 : ” + Arrays.toString(pArray3));

Person3[] pArray4 = new Person3[3]; // Person3 타입의 배열생성 OK
for (int i = 0; i < 3; i++) {

//Person3 p4 = new Person3(); // error Person3() has private access

System.out.print(“\n\nEnter Person name and age : “);
Person3.setName(input.next()); // p4.setName(input.next()) 사용을 못하게 함
Person3.setAge(input.nextInt()); // p4.setAge(input.nextInt()) 사용을 못하게 함

//pArray3[i] = p4; // error p4 객체를 생성할 수 없으므로 사용 불가능

}

Person3.print();

Lab3

Lab3 프로젝트 디렉토리 안에 모든 파일(src/*.java & bin/*.class)와 보고서 (2~3장)를 넣고 Lab3_학번_이름.zip 압축한 후 e-learning

(http://lms.dankook.ac.kr/index.jsp)으로 제출 ()

Lab3 – Class/OOP

수업블로그에 클래스 OOP 참고하여, 본인이 작성한 Lab2를 객체지향적인 프로그램으로 바꾼다. 그리고 본인이 원하는 Converter 클래스를 하나더 추가 작성한다 (예시: degree <-> radian 변환, kilometer <-> mile 변환, kilogram <-> pound 변환, 등등). ConverterMode 를 사용해줄 것!

http://www.unitconverters.net/
보고서는 출력해서 수업시작 전에 제출한다.

보고서의 내용은 기존 코드 분석과 이해한 내용 그리고 본인이 추가한 코드내용을 적는다..

 

public enum ConverterMode {
FAHRENHEIT_TO_CELSIUS(1),
CELSIUS_TO_FAHRENHEIT(2),
KILOMETER_TO_MILE(3),
MILE_TO_KILOMETER(4);

private final int type;
ConverterMode(int type) {
this.type = type;
}
public int getType() {
return type;
}
public static ConverterMode valueOf(int value) {
switch(value) {
case 1: return FAHRENHEIT_TO_CELSIUS;
case 2: return CELSIUS_TO_FAHRENHEIT;
case 3: return KILOMETER_TO_MILE;
case 4: return MILE_TO_KILOMETER;
}
return null;
}
}

 

// main

public static void main(String[] args) {
calculate(1);
calculate(2);
calculate(3);
calculate(4);

for (ConverterMode c: ConverterMode.values()) {
calculate(c);
}
}