Constructor usage guideline

// private constructor는 정적 메소드와 필드 (static method & field)만 있는 경우 사용함.

class Counter {
    private Counter() { }
    public static int currentCount;
    public static int IncrementCount() { return ++currentCount; }
}

class TestCounter {
    public static void main(String[] args) {
        // If you uncomment the following statement, it will generate
        // an error because the constructor is inaccessible:
        //Counter aCounter = new Counter(); // Error
        Counter.currentCount = 100;
        Counter.IncrementCount();
        System.out.println("count=" + Counter.currentCount); // count=101
    }
}

 

// 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 Rectangle extends Shape {
    private double width, height;
    public Rectangle(String name) { 
        super(name); 
        this.width = 2; 
        this.height = 3; 
    }
    @Override
    public void print() {
        super.print();
        System.out.printf(" 가로: %f 세로: %f\n", this.width, this.height);
    }
}

public class Triangle extends Shape {
    private double bottom, height;
    public Triangle(String name) { 
        super(name); 
        this.bottom = 1; 
        this.height = 1; 
    }
    @Override
    public void print() {
        super.print();
        System.out.printf(" 밑변: %f 높이: %f\n", this.bottom, this.height);
    }
}

class ShapeTest {
    public static void main(String[] args) {
        //Shape s1 = new Shape("도형"); // Error; Shape is abstract; cannot be instantiated
        Shape s = new Triangle("삼각형");
        s.print(); // 삼각형 밑변: 1 높이: 1
        s = new Rectangle("직사각형");
        s.print(); // 직사각형 가로: 2 세로: 3
    }
}

Lab3

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

Lab3 class/OOP

java1-lab3

보고서는 출력해서 수업시작 전에 제출한다.

WindChillTemperatureIndex 열거형
EXTREME_DANGER
DANGER
WARNING
CAUTION
AWARE
public static WindChillTemperatureIndex getIndex(double value)
EXTREME_DANGER -75 F 미만 (-60 C)
DANGER -75 ~ -50 F (-60 ~ -45 C)
WARNING -50 ~ -15 F (-45 ~ -25 C)
CAUTION -15 ~ 15 F (-25 ~ -10 C)
AWARE 15 ~ 32 F (-10 ~ 0 C)
그 외, null

HeatIndex 열거형
EXTREME_DANGER
DANGER
EXTREME_CAUTION
CAUTION
public static HeatIndex getIndex(double value)
EXTREME_DANGER 130 F 이상 (54 C 이상)
DANGER 105 ~ 130 F (41 ~ 54 C 미만)
EXTREME_CAUTION 90 ~ 105 F (32 ~ 41 C 미만)
CAUTION 80 ~ 90 F (27 ~ 32 미만)
그 외, null

BankAccount Instance Static

BankAccount-InstanceStatic – instance vs static member field & method
BankAccount-InstanceStatic

import java.util.*;
public class BankAccount {
    private int balance;
    private static int interestRate; // (%)

    public BankAccount() { 
        balance = 0; 
        interestRate = 5; 
    }

    public void deposit(int amount) { 
        balance += amount;
    }
   
    public void withdrawl(int amount) { 
        balance -= amount; 
    }

    public void print() { 
        System.out.println("final balance=" + 
	        (balance + balance * interestRate * 0.01) +
		" balance=" +
		balance +
		" interest=" +
		(balance * interestRate * 0.01));
		printInterestRate(); 
    }

    public static void setInterestRate(int interestRate) { 
        BankAccount.interestRate = interestRate; 
    }

    public static void printInterestRate() { 
        System.out.println("interestRate=" +
        interestRate); 
    }

    public int getUserInputInt() {
        Scanner input = new Scanner(System.in);
        System.out.print("Please enter Integer value: ");
        int value = input.nextInt();
        return value;
    }

    public static void main(String[] args) {
        BankAccount b = new BankAccount();
        b.deposit(2000);
        b.withdrawl(1000);
        b.print();
        BankAccount.printInterestRate();

        int amount = b.getUserInputInt();
        b.deposit(amount);
        b.print();
    }
}

ValueClass Instance Static

ValueClass-InstanceStatic

Instance member field: int value

Static member field: static int count

public class ValueClass {
    private int value = 0; // instance field
    private static int count = 0; // static field
    static Scanner input = new Scanner(System.in); // static field

    public ValueClass() { 
	this(0); 
    }

    public ValueClass(int value) { 
        this.value = value;
        count++;
    }

    public void setValue(int value) { // instance method
        this.value = value; 
    }

    public int getValue() { // instance method
        return this.value; 
    }

    public void print() { // instance method
        System.out.println("value=" + this.value + " # of value=" + count);
    }

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

    public static void printString(String str) { // static method
        System.out.print(str);
    }

    public static int getUserInputInt() { // static method
        int value = input.nextInt();
        return value;
    }

    public static void main(String[] args) {
        ValueClass v = new ValueClass();
        v.print();
        v.setValue(2000);
        int value = v.getValue();
        v.print();

        ValueClass.printString("Please enter the integer value: ");		
        int val = ValueClass.getUserInputInt();
        v.setValue(val);
        v.print();

        ValueClass v2 = new ValueClass(300);
        v2.print();

        ValueClass[] vArray = new ValueClass[3];
        for (int i=0; i<3; i++) {
            ValueClass v3 = new ValueClass();
            ValueClass.printString("Please enter the integer value: ");
            v3.setValue(ValueClass.getUserInputInt());
            vArray[i] = v3;
        }
    }
}

instance vs static member field and method in class

PersonTest-InstanceStatic

PersonTest-InstanceStatic – instance member field & method vs static member field & method

public class Person {
    String name; // instance member field
    int age; // instance member field
    
    public Person() { // default constructor
        this("JAVA", 20); // 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) { // instance method
        this.age = age;
    }

    public String getName() { // instance method
        return name;
    }

    public int getAge() { // instance method
        return age;
    }

    public void print() { // instance method
        System.out.println("Person Name=" + name + " Age=" + age);
    }

    @Override
    public String toString() { // instance method
        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("JAVA", 20); // 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=" + name + " Age=" + age; // instance method에서는 static member variable 접근 가능
    }
}

public class Person3 {
    static String name; // static member field
    static int age; // static member field

    private Person3() { // private 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[] pArray1 = new Person[3]; 
        // 아래와 같이 for문 안에 Person p = new Person()와같이 
        // 새로운 객체를 생성해야 각자 다르게 입력된 정보가 들어가게 됨 
        for (int i = 0; i < 3; i++) {
            Person p1 = new Person(); 
            System.out.print("\n\nEnter Person name and age : ");
            p1.setName(input.next()); // 입력정보
            p1.setAge(input.nextInt()); // 입력정보
            p1.Print();
            pArray1[i] = p1; // p1는 새로운 Person객체이므로 배열에서 각각 다른 원소가 들어간다  
        } 
        System.out.println("pArray1 : " + Arrays.toString(pArray1)); 

        // 만약 Person2 객체의 name과 age는 static이라서,  
        // static은 공유하는 것이므로, 마지막으로 입력된 데이터로 모든 데이터값이 치환됨 
        Person2[] pArray2 = new Person2[3]; 
        for (int i = 0; i < 3; i++) {  
            Person2 p2 = new Person2(); 
            System.out.print("\n\nEnter Person name and age : ");
            p2.setName(input.next()); // Person2.setName(input.next())와 동일
            p2.setAge(input.nextInt()); // Person2.setAge(input.nextInt())와 동일
            pArray2[i] = p2; // p2 객체의 name과 age는 static이므로 모두 공유하기때문에, 배열의 모든 원소는 마지막에 들어간 정보로 셋팅
        }
        System.out.println("pArray2 : " + Arrays.toString(pArray2));
 
        Person3[] pArray3 = new Person3[3]; // Person3 타입의 배열생성 OK 
        for (int i = 0; i < 3; i++) {  
            //Person3 p3 = new Person3(); // error Person3() has private access 
            System.out.print("\n\nEnter Person name and age : ");
            Person3.setName(input.next()); // p3.setName(input.next()) 사용을 못하게 함
            Person3.setAge(input.nextInt()); // p3.setAge(input.nextInt()) 사용을 못하게 함
            //pArray3[i] = p3; // error p3 객체를 생성할 수 없으므로 사용 불가능  
        } 
        Person3.print();

default, public, protected, private

default (package private – access in other classes within the same package)

public (visible everywhere)

protected (only access in its own class, its subclass and other classes within the same package)

private (only access in its own class)

http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

Access Levels
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N

 

C# Parameter Passing

pass value type by value (값형식을 값에 의한 전달)

static void Square1(int x)
{
x *= x;
Console.WriteLine(“The value inside the method: {0}”, x);
}
static void Main()
{
int i = 5;
Console.WriteLine(“i={0}”, i);
Square1(i);
Console.WriteLine(“i={0}”, i);
}
//i=5
//The value inside the method: 25
//i=5

 

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

static void ChangeArray1(int[] arr)
{
arr[0]=888; // arr -> myArray이므로 원본 배열의 첫번째 값은 888로 변경
Console.WriteLine(“arr=” + string.Join(“,”, arr)); // .NET4만 동작
//Console.WriteLine(“arr=” + string.Join(“,”, Array.ConvertAll(arr, x => x.ToString()))); // .NET4  Earlier
arr = new int[5] {-3, -1, -2, -3, -4}; // local 변수로 새롭게 할당하여 지정
Console.WriteLine(“arr=” + string.Join(“,”, arr)); // .NET4
}
static void Main()
{
int[] myArray = {1, 4, 5};
Console.WriteLine(“myArray=” + string.Join(“,”, myArray)); // .NET4
ChangeArray1(myArray);
Console.WriteLine(“myArray=” + string.Join(“,”, myArray)); // .NET4
}
//myArray=1, 4, 5
//arr=888, 4, 5
//arr=-3, -1, -2, -3, -4
//myArray=888, 4, 5

 

 

pass value type by reference (값형식을 참조에 의한 전달)
ref 키워드 사용

static void Square2(ref int x)
{
x *= x;
Console.WriteLine(“The value inside the method: {0}”, x);
}
static void Main()
{
int i = 5;
Console.WriteLine(“i={0}”, i);
Square2(ref i);
Console.WriteLine(“i={0}”, i);
}
//i=5
//The value inside the method: 25
//i=25

 

pass reference type by reference (참조형식을 참조에 의한 전달)
ref 키워드 사용

static void ChangeArray2(ref int[] arr)
{
arr[0]=888; // 원본 배열의 첫번째 값은 888로 변경
Console.WriteLine(“arr=” + string.Join(“,”, arr)); // .NET4만 동작
arr = new int[5] {-3, -1, -2, -3, -4}; // 원본 배열이 다시 변경
Console.WriteLine(“arr=” + string.Join(“,”, arr)); // .NET4만 동작
}
static void Main()
{
int[] myArray = {1, 4, 5};
Console.WriteLine(“myArray=” + string.Join(“,”, myArray)); // .NET4
ChangeArray2(ref myArray);
Console.WriteLine(“myArray=” + string.Join(“,”, myArray)); // .NET4
}
// myArray=1, 4, 5
// arr=888, 4, 5
// arr=-3, -1, -2, -3, -4
// myArray=-3, -1, -2, -3, -4

 

pass value type by output (값형식을 output에 의한 전달)
out 키워드 사용

static void Square3(int x, out int result)
{
result = x*x;
Console.WriteLine(“The value inside the method: {0}”, result);
}
static void Main()
{
int i = 5;
Console.WriteLine(“i={0}”, i);
int result;
Square3(i, out result);
Console.WriteLine(“result={0}”, result);
}
//i=5
//The value inside the method: 25
//result=25

 

pass reference type by output (참조형식을 output에 의한 전달)
out 키워드 사용

static void ChangeArray3(out int[] arr)
{
//arr[0]=888; // use of unassigned out parameter ‘arr’ ERROR
arr = new int[5] {-3, -1, -2, -3, -4}; // 원본 배열이 변경
Console.WriteLine(“arr=” + string.Join(“,”, arr)); // .NET4
}
static void Main()
{
int[] myArray = {1, 4, 5};
Console.WriteLine(“myArray=” + string.Join(“,”, myArray)); // .NET4
ChangeArray3(out myArray);
Console.WriteLine(“myArray=” + string.Join(“,”, myArray)); // .NET4
}
//myArray=1, 4, 5
//arr=-3, -1, -2, -3, -4
//myArray=-3, -1, -2, -3, -4

 

Java swap pass-by-value


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

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

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

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

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

// Java uses pass-by-value
static void swap2(Point p, Point q) {
    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
}