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

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

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
}

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.x);
    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

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

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

Break a loop if q-key is pressed

// break a loop if 'q'-key is pressed
static Scanner scan = new Scanner(System.in);
public static boolean getUserInputExitKey() {
    System.out.println("Please enter key to continue or the q-key to exit.");
    String input = scan.nextLine();
    if (input == null || input.contentEquals("")) return false;
    if (input.contentEquals("q")) return true;
    else return false;
}

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

do {

// do whatever..

} while(!getUserInputExitKey());

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