본문 바로가기
STUDY/JAVA

Java 8일차

by Anne of Green Galbes 2019. 1. 29.

1. 생성자

① 생성자 사용 이유

    - 메모리를 할당 받을때 사용

    - 변수 초기화를 목적으로 사용

② 생성자 선언

    - 생성자의 이름은 클래스의 이름과 동일해야한다.

    - 리턴값이 없어 property가 없다. 

    - 중복정의(overloading)가 가능하다.

    - 코딩의 첫째불에서 한번 만 호출 가능하다.

③ 생성자를 선언 안하면 기본생성자가 자동으로 생성

    - public 클래스이름(){}


예제 1

public Test1() { } : 기본생성자 / 변수 초기화

public Test(int x) { } : 오버로딩된 생성자

package com.day08;


public class Test1 {

private int x;

public Test1(){

this(100);

System.out.println("기본생성자(인수가 없는 생성자)");

x=10;

System.out.println("x:" +x);

}

public Test1(int x){

System.out.println("중복정의된 생성자");

this.x=x;

System.out.println("x:" +x);

}

public void set(int x){

this.x = x;

}

public static void main(String[] args) {

Test1 ob1 = new Test1();

Test1 ob2 = new Test1(20);

}

}

결과

중복정의된 생성자

x:100

기본생성자(인수가 없는 생성자)

x:10

중복정의된 생성자

x:20




예제 2

package com.day08;


class Rect{

private int w;

private int h;

public Rect(){ //기본생성자

}

public Rect(int w, int h){ //오버로딩된 생성자

this.w = w;

this.h = h;

}

public void set(int w, int h){

this.w = w;

this.h = h;

}

public int area(){

return w*h;

}

public int length(){

return 2*(w+h);

}

public void print(int a, int l){

System.out.println("가로:" +w);

System.out.println("세로:" +h);

System.out.println("넓이:" +a);

System.out.println("둘레:" +l);

}

public void print(int a){ //메소드 오버로딩(중복정의)

System.out.println("가로:" +w);

System.out.println("세로:" +h);

System.out.println("넓이:" +a);

}

}


public class Test2 {

public static void main(String[] args) {

Rect ob1 = new Rect();

ob1.set(10, 20);

int area = ob1.area();

int length = ob1.length();

ob1.print(area);

ob1.print(area, length);

System.out.println("-----------");

Rect ob2 = new Rect(100,200); //의존성주입

area = ob2.area();

length = ob2.length();

ob2.print(area);

ob2.print(area, length);

}

}

결과

가로:10

세로:20

넓이:200

가로:10

세로:20

넓이:200

둘레:60

-----------

가로:100

세로:200

넓이:20000

가로:100

세로:200

넓이:20000

둘레:600



2. 초기화 블럭 & 정적(static)블럭

package com.day08;


public class Test3 {

int a = 5;

{ //초기화 블럭

System.out.println("초기화 블럭 a ->:" +a);

a=10;

System.out.println("초기화 블럭 a ->:" +a);

}

static int b;

static{ //static 블럭

b=20;

System.out.println("static 블럭 b ->:" +b);

}

final int C; //final(상수)

public Test3(){

System.out.println("생성자...");

C = 100;

System.out.println("C:" +C);

}

public static void main(String[] args) {

Test3 ob = new Test3();

Test3 ob1 = new Test3();

}

}

▶ static은 자동으로 실행

▶ 블럭이 실행 된 후 생성자 실행

결과

static 블럭 b ->:20

초기화 블럭 a ->:5

초기화 블럭 a ->:10

생성자...

C:100

초기화 블럭 a ->:5

초기화 블럭 a ->:10

생성자...

C:100



3 되부름 함수 / 비정형 인수

① 되부름 함수 : 자기자신을 다시 호출하는 함수

    - 장점 : 소스가 간단해진다.

    - 단점 : 처리속도가 느려진다. → static에 저장했다가 출력하기 때문에

② 비정형 인수 : 매개변수의 갯수가 고정인 아닌 경우

package com.day08;


public class Test4 {

//되부름 함수

public void print(int n){

if(n!=1){

print(n-1);

}

System.out.printf("%5d", n);

}

public int sum(int n){

return n>1?n+sum(n-1):n;

}

public int pow(int a, int b){

return b>=1?a*pow(a,b-1):1;

}

//비정형인수

int sum(int...args){

int sum = 0;

for(int i=0;i<args.length;i++)

sum += args[i];

for(int su:args){

sum += su;

}

return sum;

}

public static void main(String[] args) {

Test4 ob = new Test4();

ob.print(5);

int s = ob.sum(100);

System.out.println();

System.out.println(s);

System.out.println("pow(2,10):" +ob.pow(2,10));

//비정형인수

int result;

result = ob.sum(2, 4, 6, 8, 10);

System.out.println(result);

result = ob.sum(1, 3, 5, 7, 9, 11 ,13 ,15 ,17);

System.out.println(result);

}

}


결과

    1    2    3    4    5

5050

pow(2,10):1024

60

162



4. 계산기 : 숫자 2개 입력 / 연산자 입력

package com.day08;


import java.io.IOException;

import java.util.Scanner;


class Calc{

private int num1, num2;

private char oper;

public boolean input() throws IOException{

Scanner sc = new Scanner(System.in);

System.out.print("두개의 수:");

num1 = sc.nextInt();

num2 = sc.nextInt();

System.out.print("연산자[+,-,*,/]:");

oper = (char)System.in.read();

if(oper!='+' && oper!='-' && oper!='*' && oper!='/'){

return false;

}

return true;

}


public int result(){

int r = 0;

switch(oper){

case '+':

r = num1 + num2; break;

case '-':

r = num1 - num2; break;

case '*':

r = num1 * num2; break;

case '/':

r = num1 / num2; break;

}

return r;

}

public void print(int r){

System.out.printf("%d %c %d = %d \n", num1, oper, num2, r );

}

}



public class Test5 {

public static void main(String[] args) throws IOException {

Calc ob = new Calc();

int r = 0;

if(!ob.input()){

System.out.println("연산자 오류!");

return;

}

r = ob.result();

ob.print(r);

}

}


결과

두개의 수:10 20

연산자[+,-,*,/]:+

10 + 20 = 30 



5 Call By Value & Call By Reference

① 메모리 사용 영역


② Call By Value & Call By Reference

 Call By Value

   - 값에 의한 호출 

   - stack영역의 데이터가 Heap영역으로 데이터 자체가 넘어감

○ Call By Reference

   - 주소를 호출

   - Heap영역의 데이터를 복사할 때 객체가 아닌 주소를 복사

package com.day08;


class Test{

public int x = 10;

public void sub(int a){

x+=a;

}

}


public class Test6 {

public static void main(String[] args) {

Test ob = new Test();

int a = 10;

System.out.println("sub메소드 실행전:" + ob.x);

ob.sub(a); //Call by Value

System.out.println("sub메소드 실행후:" + ob.x);

//Call By Reference

Test ob1;

ob1 = ob;

System.out.println("ob.x:" +ob.x);

System.out.println("ob1.x:" +ob1.x);

ob1.x = 100;

System.out.println("ob.x:" +ob.x);

System.out.println("ob1.x:" +ob1.x);

}

}


결과

sub메소드 실행전:10

sub메소드 실행후:20

ob.x:20

ob1.x:20

ob.x:100

ob1.x:100



6.  상속

상속 : 부모가 자식에게 물려주는 행위

① 부모꺼는 자식이 사용 가능하다.

② private로 선언한 것은 상속이 불가능하다.

③ protected로 선언한 것은 상속이 가능하다.

④ 자식꺼는 부모가 사용이 불가능하다.

⑤ 부모와 내가 똑같은 것을 가지고 있으면 내꺼를 사용한다.

⑥ 여러개의 부모 클래스를 상속할 수 없다.

⑦ 선언 방법

    class 자식클래스 extends 부모클래스 {

//필드

//생성자

//메소드

    }

    class 자식클래스 extends 부모클래스1, 부모클래스2 {

    }        ▶ 불가


예제 1

package com.day08;


class SuperClass{

private String title;

private int area;

public void set(String title, int area){

this.area = area;

this.title = title;

}

public void print(){

System.out.println(title+ ":" +area);

}

}


class SubClass extends SuperClass {

private int w;

private int h;

public SubClass(int w, int h){

this.w = w;

this.h = h;

}

public void rectArea(){

int a = w*h;

set("사각형", a);

}

}


public class Test7 {

public static void main(String[] args) {

SubClass ob = new SubClass(10, 20);

ob.rectArea();

ob.print();

}

}


결과

사각형:200



예제 2

package com.day08;

class SuperClassA{
private String title;
protected int area;
public void set(String title){
this.title = title;
}
public void print(){
System.out.println(title+ ":" +area);
}
}
class SubClassA extends SuperClassA {
private int w;
private int h;
public SubClassA(int w, int h){
this.w = w;
this.h = h;
}
public void rectArea(){
area = w*h;         //③ protected로 선언한 것은 상속이 가능하다.

set("사각형");
}
}
public class Test8 {
public static void main(String[] args) {
SubClassA ob = new SubClassA(100, 200);
ob.rectArea();
ob.print();             //▶① 부모꺼는 자식이 사용 가능하다
ob.area = 100;    //③ protected로 선언한 것은 상속이 가능하다.
ob.print();            //① 부모꺼는 자식이 사용 가능하다
}
결과
사각형:20000 사각형:100


'STUDY > JAVA' 카테고리의 다른 글

Java 20일차(2) - 회원가입 DB연결하여 만들기  (0) 2019.02.01
Java 20일차(1) -자바 오라클 연결, Statement  (0) 2019.02.01
Java 7일차  (0) 2019.01.28
Java 6일차  (0) 2019.01.24
Java 5일차  (0) 2019.01.24

댓글