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
    }
}

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

 

Person Array

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

Person[] pArray = new Person[5];
// 아래와 같이 for문 안에 Person p = new Person()와같이
// 새로운 객체를 생성해야 각자 다르게 입력된 정보가 들어가게 됨
for (int i = 0; i < 5; i++) {
    Person p = new Person();
    System.out.print("\n\nEnter Person name : ");
    Scanner input = new Scanner(System.in);
    p.setName(input.nextLine()); // 입력정보
    System.out.print("\n\nEnter Person age [int] : ");
    p.setAge(input.nextInt()); // 입력정보
    p.print();
    pArray[i] = p; // 이때 p는 새로운 Person객체
}
System.out.println("pArray2 : " + Arrays.toString(pArray2));

returning an array from a method vs passing an array as parameter to a method

// returning an array from a method vs passing an array as parameter to a method

// passing an array as parameter to a method
public static int sumArray(int[] arr) {
	int sum = 0;
	for (int i = 0; i < arr.length; i++) {
		sum += arr[i];		
	}
	return sum;
}

// returning an array from a method
public static int[] assignArray(int length) {
	int[] arr = new int[length];
	for (int i = 0; i < arr.length; i++) {
		arr[i] = i;
	}
	return arr;
}

////////////////////////////////////// in main
// returning an array from a method
int[] arr1 = assignArray(3);
int[] arr2 = assignArray(5);
for (int e : arr1)	System.out.println(e); // 0 1 2
for (int e : arr2)	System.out.println(e); // 0 1 2 3 4

// passing an array as parameter to a method
int[] array1 = {100, 200, 300};
int[] array2 = {50, 60, 70, 80, 90};
int sum1 = sumArray(array1);
int sum2 = sumArray(array2);
System.out.println("array1 sum=" + sum1); // 100 + 200 + 300 = 600
System.out.println("array2 sum=" + sum2); // 50 + 60 + 70 + 80 + 90 = 350

Object-Oriented Programming (OOP)

Object − objects have states and behaviors.
Class – defines the grouping of data and code, the “type” of an object
Instance – a specific allocation of a class
Message – sent to objects to make them act
Method – a “function” that an object knows how to perform
Local Variables − variables defined inside methods, constructors or blocks
Instance Variables – variables within a class but outside any method (a specific piece of data belonging to an object)
Class Variables − variables declared within a class, outside any method, with the static keyword
Encapsulation – keep implementation private and seperate from interface
Polymorphism – different objects, same interface
Inheritance – hierarchical organization, share code, customize or extend behaviors

2D Array

// 2D array
char[] ops = {'+', '-', '*', '/'};
int[][] numbers = {{60,50}, {40,30}, {20,10}};
for (char op : ops) {
    for (int i = 0; i < numbers.length; i++) {
        int result = calc(numbers[i][0], numbers[i][1], op);
        System.out.printf("result = %d %s %d = %d\n", numbers[i][0], op, numbers[i][1], result);
    }
}

result = 60 + 50 = 110
result = 40 + 30 = 70
result = 20 + 10 = 30
result = 60 – 50 = 10
result = 40 – 30 = 10
result = 20 – 10 = 10
result = 60 * 50 = 3000
result = 40 * 30 = 1200
result = 20 * 10 = 200
result = 60 / 50 = 1
result = 40 / 30 = 1
result = 20 / 10 = 2

Integer Array

int[] integerArray = new int[3];
integerArray[0] = 1;
integerArray[1] = 2;
integerArray[2] = 3;

for (int i : integerArray) 
    System.out.println(i);

for (int j = 0; j < integerArray.length; j++) 
    System.out.println(integerArray[ j ]);

int k = 0;
while (k < integerArray.length) 
    System.out.println(integerArray[k++]);
// int array
// 만약 int value1를 for문에서 공유해 사용한다해도 
// intArray1[i]에 값이 들어가므로 각각 다른 입력값이 들어가게 됨
int value1 = 0;
int[] intArray1 = new int[3];
for (int i = 0; i < intArray1.length; i++) {
	System.out.print("Please enter int number: ");
	value1 = scan.nextInt(); // 10 20 30
	intArray1[i] = value1;
}
for (int v : intArray1)	System.out.println(v); // 10 20 30

// int value2를 for문에서 내부에서 매번 생성해서 사용한다해도 
// intArray2[i]에 값이 들어가므로 각각 다른 입력값이 들어가게 됨
int[] intArray2 = new int[3];
for (int i = 0; i < intArray1.length; i++) {
	System.out.print("Please enter int number: ");
	int value2 = scan.nextInt(); // 100 200 300
	intArray2[i] = value2;
}
for (int v : intArray2)	System.out.println(v); // 100 200 300

Break a loop if ‘q’ key is pressed


 public static boolean getUserInputExitKey() {
    System.out.println("Please enter key to continue or the 'q' key to exit.");
    try {
        if ((char)System.in.read() == 'q') return true;
    }
    catch (IOException e) {
        System.out.println("Error user key reading");
    }
    return false;
}

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


do {

    // do whatever..

} while(!getUserInputExitKey());

Lab2

Lab2 – ImageConverterTest (Due by 4/2)
Lab2 프로젝트 디렉토리 안에 모든 파일(src/*.java & bin/*.class)와 보고서(3-4장정도 – 장수제한없음)를 넣고 Lab2_학번_이름.zip
압축한 후 e-learning(http://lms.dankook.ac.kr/index.jsp)으로 제출

0 – image convert
1 – command line arguments (inputFile, outputFile, format)
2 – for/foreach
3 – if/else, switch, constant
4 – while/do-while, Scanner 클래스를 이용하여 사용자 입력받아서 image convert한다.
5 – 본인이 원하는 코드를 추가작성한다. – 예를 들어, image resize
1,2,3,4,5에 해당하는 부분을 /* 주석문 */으로 표시해준다.


// converts an image to another format
public static boolean convert(String inputImageFile, String outputImageFile, String format) {
    boolean result = false;;
    BufferedImage image = null;
    try {
        // reads input image from file
        image = ImageIO.read(new File(inputImageFile));
        // writes to the output image in specified format
        result = ImageIO.write(image, format, new File(outputImageFile));
        // prints the result
        if (result) {
            System.out.println(inputImageFile + " Image converted to " + outputImageFile + " successfully.");
        } else {
            System.out.println("Could not convert image.");
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}

public static void print(String imageFilename) {
    // reads the image
    BufferedImage image = null;
    try {
        image = ImageIO.read(new File(imageFilename));
        int width = image.getWidth();
        int height = image.getHeight();
        String ext = imageFilename.substring(imageFilename.lastIndexOf('.')+1);
        // prints the image information
        System.out.println("filename=" + imageFilename);
        System.out.println("width=" + width);
        System.out.println("height=" + height);
        System.out.println("format=" + ext);
    } catch (IOException e) {
        e.printStackTrace();
    }
}