Java

04.21 - 메소드, 클래스

amungstudy 2023. 4. 21. 15:57

OOP(object oriented programming) :  객체 지향 프로그래밍.

 

필드 이름은 중복되면 안된다.

클래스의 필드 = 배열의 인덱스라고 생각하면 편함.

  • 파라미터와 arguments의 차이 :

파라미터는 매개변수. 메소드 실행에 필요한 데이터

arguments는 파라미터의 실제 데이터값. 

ex) 파라미터  : int a 

            arguments : 10 

 

  • void 타입 메소드에서도 return문 사용가능(함수종료 기능) / return문 뒤에 실행문 있으면 컴파일 오류
  • 반환값있는 메소드 안에 조건문이 있는 경우 어떠한 경우에라도 return있어야함.(없으면 컴파일 오류)
  • 클래스도 일종의 메소드라서 , 생성자 오버로딩 가능
  • this로 인스턴스 멤버에 접근 가능, 생성자에서도 this 사용 가능

package a_declaration;

// class block 외부에는

// class선언, package 정의, import 지정만 가능하다.

/*

int a = 0; //오류

System.out.println("오류");

*/

// public class의 이름(식별자)는 파일 이름과 동일해야한다.

public class Student {}

 

class Bus{}


package a_declaration;

// main method가 포함된 class를 실행class라고 한다.

public class StudentExample {

 

public static void main(String[] args) {

Student s1; //선언

s1 = new Student(); //초기화, 객체 생성

System.out.println("Student class를 참조하여 s1 객체 생성 -"+s1);

Student s2 = new Student();

System.out.println("Student class를 참조하여 s2 객체 생성 -"+s2);

System.out.println(s1== s2); // false

 

Bus bus = null;

bus = new Bus();

System.out.println(bus);

}

}


package b_field;

 

public class Field {

/*

* 객체의 속성, 재산, 메모리 공간 다양한 형식으로 불림

* attribute,property, field

* class block 내부에서 어디서나 사용가능한 변수 - 전역변수

* java에서는 객체의 실제 메모리에 저장되는 data라고 해서 Field라고 함.

*/

int intField;

double doubleField;

boolean booleanField;

String stringField;

 

// ; 끝나는 실행문은 Field선언만 가능

// System.out.println("안됨");

 

} // Field class end


package b_field;

/**

* 객체 모델링 - 추상화

* 현실의 대상에서 프로그래밍에 필요한 속성 및 동작을 추출하는 과정

* 공통의 속성이나 기능을 묶어 이름을 붙이는 것

*/

public class Person {

// 결혼 정보 업체

String name;

String birth;

double height;

double weight;

char gender;

boolean isMarried;

}


package b_field;

 

public class FieldExample {

 

public static void main(String[] args) {

// Field.intField; 이렇게 쓸 수 x 객체 생성해야함.

Field f1 = new Field();

int i = f1.intField;

double d = f1.doubleField;

boolean b = f1.booleanField;

String str = f1.stringField;

System.out.println("intField : " + i);

System.out.println("doubleField : " + d);

System.out.println("booleanField : " + b);

System.out.println("stringField : " + str);

 

Field f2 = new Field();

f2.intField = 100;

f2.doubleField = 3.14;

f2.booleanField = true;

f2.stringField = "확인";

 

 

}

 

}


package c_method;

 

// 탁상용 램프

public class DarkLamp {

 

// 인스턴스 멤버 변수 선언

boolean isOnOff;

 

void setSwitch(boolean isOnOff) {

this.isOnOff = isOnOff; //this는 전역변수랑 지역변수 구분 위해서 사용함. // this에는 instance의 주소값을 들고 있음.

System.out.println(this);

 

 

}

 

String showInfo() {

return "현재상태는 " + (isOnOff?"켜짐":"꺼짐");

}

 

public static void main(String[] args) {

DarkLamp dl = new DarkLamp();

System.out.println(dl);

dl.setSwitch(true); // this에는 instance의 주소값을 들고 있음.

dl.setSwitch(false);

}

 

}


package c_method;

 

public class MethodExample {

// 반환타입 식별자(매개변수...){실행문}

void methodA() {

// void 반환하는 값이 존재하지 않음

System.out.println("반환하는 값이 없고 매개변수가 없이 기능만 수행");

}

// 메소드를 호출하기 위한 접근자인 식별자는 중복이 되면 안된다.

// int methodA() {}

 

int methodB() {

System.out.println("매개변수는 없지만 내부 연산을 통해 정수값을 반환");

return 0;

}

 

// 매개변수

double methodC(int a,int b) {

System.out.println("int type이 매개변수 두개를 전달받아");

System.out.println("double type의 값을 반환");

return a/(double)b;

}

 

 

 

public static void main(String[] args) {

MethodExample me = new MethodExample();

// 아래와 같이 작성시 오류가 발생하는 이유 1. 메소드의 반환값이 없다 || 2. 반환값 타입이 일치하지 않다.

// String s = me.methodA();

 

int result = me.methodB();

System.out.println("methodB result :" + result);

 

double doubleValue = me.methodC(10, 3);

System.out.println(doubleValue);

 

boolean isTrue = me.methodD(10,20); // 호출문만 써도 이클립스가 아래에 method자동완성 가능~!(f2번)

 

me.methodE(10,20,30);

}

// 매개변수 3개가 존재하고 반환하는 값이 존재하지 않는 method

void methodE(int i, int j, int k) {

 

}

// 매개변수를 전달받아 연산 후 boolean type의 값을 반환하는 함수

boolean methodD(int i, int j) {

return (i>j)?true:false;

}

}


package c_method;

 

/**

* 동일한 메소드 이름으로 다양한 기능을 정의할 수 있는 방법

* method overloading

* 1. 매개변수의 타입 차이

* 2. 매개변수의 개수 차이

* 3. 매개변수의 타입이 상이할 때 순서 차이

*/

 

public class MethodOverloading {

 

void methodA() {}

void methodA(int score) {}

void methodA(double b) {}

void methodA(int score, double result) {}

void methodA(double result, int score) {}

// void methodA(int score, int result) {}

// void methodA(int result, int score) {} // 이거는 오류발생.

 

// void methodA(int score1, int score2) {}

// void methodA(int score1, int score2, int score3) {}

// 가변형 인자열

void methodA(int... scores) { //매개변수 전달 받을 때 개수와 상관없이 받음, 배열로 생성됨.

 

//전달 받은 점수로 총점을 출력

System.out.println("가변형 인자열 methodA 호출");

int sum = 0;

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

sum += scores[i];

}

System.out.println("총점 : "+sum);

}

 

// void methodB(int... scores, String name) { //가변형 인자열의 매개변수가 몇개나 올 지 모른다. 오류남.

 

// }

void methodB(String name, int... scores) {

 

}

 

public static void main(String[] args) {

MethodOverloading mo = new MethodOverloading();

mo.methodA(10,30.0);

// 가변형 인자열 method 호출

mo.methodA(10,20,30);

mo.methodA(10,20,30,40,50,60,70);

mo.methodB("꽃님반",20,30,50,60);

}

 

}


package d_constructor;

 

public class Car {

String company; //제조회사

String model; // 모델명

String color; // 색상

int maxSpeed; //최대속도

int speed; //현재속도

 

//생성자 정의 (반환 타입 없어야함)

Car(){

System.out.println("Car 기본 생성자 호출");

}

 

Car(String company){ //매개변수 이름 직관적으로 작성.

this.company = company; // 필드이름이랑 같아지니까 this 사용.

}

 

Car(String c, String m, int i){ // 이렇게 작성하면 다른 사람이 실행클래스에서 알기 어렵다.

company = c;

model = m;

maxSpeed = i;

}

 

Car(String company, String model, String color){

this.company = company;

this.model = model;

this.color = color;

System.out.println("3개의 문자열을 전달받는 생성자 호출");

}

 

// alt + s + a 엔터 : 생성자 생성 단축키

Car(String company, String model, String color, int maxSpeed, int speed){

//생성자 내부에서 다른 생성자 호출 (생성자의 실행문 중에 제일 위에 있어야 함) -> 중복된 코드 줄일 수 있다.

this(company,model,color);

/*

this.company = company;

this.model = model;

this.color = color;

*/

this.maxSpeed = maxSpeed;

this.speed = speed;

 

}

 

 

 

// 이 클래스에 있는 요소들이 뭔지 자동으로 만들어주는거

// alt + s +s +s 엔터

public String toString() {

return "Car [company=" + company + ", model=" + model + ", color=" + color + ", maxSpeed=" + maxSpeed

+ ", speed=" + speed + "]";

}

}


package d_constructor;

 

public class CarExample {

 

public static void main(String[] args) {

 

Car car = new Car();

car.company = "Benz";

car.model = "S class";

car.color = "Black";

car.maxSpeed = 320;

car.speed = 0;

System.out.println(car);

 

Car car2 = new Car("KIN");

car2.model = "모닝";

car2.color = "GOLD";

car2.maxSpeed = 180;

car2.speed = 0;

System.out.println(car2);

 

Car car3 = new Car("현대", "싼타페", "쥐색", 280, 0);

System.out.println(car3);

 

 

}

}