1. JAVA/3). 자바_개념

자바_개념_Day_14

구이제이 2024. 1. 18. 18:17

목차

 

ㅡㅡㅡ

1.개념설명

 

ㅡㅡㅡ

2.car //클래스 생성, 생성자하고 메소드하고 똑같다.

 

ㅡㅡㅡ

3.car2 //Car와 Car2의 클래스의 차이가, 생성자에서도 변수의 값을 입력할수있다.

 

ㅡㅡㅡ

4.Student //클래스생성



ㅡㅡㅡ

5.Student2 //생성자도 오버로딩이 되는구나.

.

 

ㅡㅡㅡ

6.Student3 //필드와 생성자안에 있는 지역변수의 차이와 구분 : this

//생성자안에서 this();

1)생성자안에서만 쓸수있다.(this.이거랑 좀 다르다.)

2)생성자에 가장 첫줄에 써야한다.

 

ㅡㅡㅡ

7.car 

 

ㅡㅡㅡ

8.Calculator



 









◐클래스

변수 > 배열 > 구조체 > 클래스

(불편함을 깨닫고 이런것을 만들었다.)

 

생성자

생성자 생략가능하지만, 컴파일러가 생성한다.

생성자 있어야지만, 힙이라는 영역에 객체를 만들고 초기화(준비)를 시켜준다.

 

1.절차 지향형(기능중심) 프로그램 : 순서에 맞추어 단계적으로 실행하도록 명령을 나열

 (이거다음에 이거, 순서대로 진행되는 것, 메소드, 배열 절차진행적)

순서바꿀수있는거 조건문과 반복문



2.객체 지향형(객체중심) 프로그램 : 객체를 구성하고 객체 단위로 프로그램을 작성(순서보다 ,필드, 메소드이용하는 것)



3.객체 지향 요소

1).클래스(CLASS)

a.일반클래스

b.추상(abstract) 클래스 : 공통점을 뽑아줘서 : 자신에게 맞게 다시 만들게한다.

(추상 -미완성)

 

public (void)

타입 - int,double,student,

 

a).완성메소드 =  public asd void show(){} 

b).미완성메소드 = public abstract void show(); => 중괄호( {} )가 없다 

 

힙 = 미완성, 채워지지 않은것들은 못올라간다 - 추상메소드는 못만든다

객체 = 힙에다가 올린다라는 뜻

 

 추상클래스는 = 완성,미완성메소드 생성자 가지고있다.

추상메소드(미완성메소드)를 하나라도 가지고 있어도 

추상클래스라 부른다.(인터페이스와 구분)

 

 

2).인터페이스(interface) : 모든 필드는 public static final(상수)

모든 메소드는 public abstract 메소드명(); - 모든 메소드는 미완성

(추상클래스를 심화시킨것이 인터페이스이다.)

(인터페이스는 무조건 미완성)

(자식들이 다 구현해야한다)

 

인터페이스는 모두다 추상메소드이다.(추상클래스는 하나만이라도있어서)

(인터페이스로 인해 다형성이라는게 만들어진다.)

 

#다형성

다형성의성질 - 

어디서든 쓸수있게 / 바로쓸수있을지 / 문제없게

 

(인터페이스 - 뭔가를 추가하더라도 문제가 생기지 않게 하는 것)

(인터페이스 = 역할을 규정 - 나머지는 알아서 구현하게)

 

 



4.클래스의 활용

  • 파일 이름과 클래스 이름은 동일해야 함

package : java파일의 폴더(패키지) 위치,

 

import : 다른 폴더(패키지) 위치의 클래스를 참조

 

[접근지정자] : 생략을 하면 디폴트/패키지

 

[접근지정자] class 클래스명(){

필드(=field, 멤버변수, 인스턴스 변수) : 클래스 ‘특징’(다른말로 ‘속성’)

생성자 : 객체 생성 기능 가지고 있다.

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

메소드(=method) : 클래스의 기능

 

[접근지정자] 리턴(=반환)타입 메소드이름(매개변수){실행문자}

(생략가능)

 

  • 클래스의 멤버 : 필드, 메소드

 

5. 클래스와 ‘객체’(‘Object’, ‘인스턴스’)

누구의 의해 만들어진거야 = ‘인스턴스’라 부른다.(명확하게 하고싶을때 부른다)

ex) student클래스로 만들어진 인스턴스야.

 

class = 설계도, 틀, 붕어빵 기계

object = class의 instance, 클래스를 이용해서 만들어내는 것

힙영역에 만들어짐(필드, 메소드..)

 

6. 객체 만들기

1)클래스 만들기(=설계도)

2)클래스를 이용해서 객체를 생성

클래스명 참조변수명 = new 생성자();

3)객체를 사용

참조변수명.필드

참조변수명.메소드명();

 

 

클래스명 필드이름 메소드

타입 반환타입 메소드명 매개변수타입



+ : public 

-  : private (캡슐화)

# : protectied  

~ : defalut : 내패키지안에서 자유롭게 쓸수있다.

 

private에서?

getter(값을 가져오는것)

setter(값을 변경)




Car1



public class Car {

//#1.필드

String company = "현대자동차"; // String company;

String model = "그랜저";

String color = "검정";

int maxSpeed = 300;

int speed;

 

//#2.생성자 - 생략하면 컴파일러가 컴파일시 자동으로 생성

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

 

}

 

 

 

//#3.메소드

public void show() {

System.out.println("자동차 이름 : " + company);

if(speed >= maxSpeed) {

System.out.println("속도가 최대치를 초과했습니다.");

System.out.println("속도를 다시 설정해 주세요");

}

}

 

 

}




Car1의 메인

//#1. Car클래스를 이용해서 객체를 생성

Car car = new Car(); //여러번 쓸때, 이렇게 한다. //붕어빵1번

 

//new Car(); - 한번 쓸거면 이렇게 생성할수도 있다.(어느것

 

//1)변수선언과 초기화

//Car car; 변수선언

//car = new Car(); 변수 초기화

 

//2)변수선언과 초기화

//Car car = new Car(); //여러번 쓸때, 이렇게 한다.

 

 

Car car1 = new Car(); //붕어빵2번

Car car2 = new Car(); //붕어빵3번

 

//(Car) 타입이다 ex)int,double,String 등등

//(Car)는 참조타입이다.

//생성자는 클래스타입과 같은 이름이여야 한다

 

 

//#2. 객체 사용

System.out.println("붕어빵1번");

System.out.println("car.company : "  + car.company);

System.out.println("car.model : "  + car.model);

System.out.println("car.color : "  + car.color);

System.out.println("car.maxSpeed : "  + car.maxSpeed);

System.out.println("car.speed : "  + car.speed);

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

 

//★★★ 클래스에서, 리턴으로 들어오는 것과 그렇지 않은 것의 차이

//1)클래스의 메소드 실행

// System.out.println("메소드 실행 : "  + car.show());

//메소드는 프린트안에 집어넣을수없다.

//왜냐면, show()자체가 실행문장이에요.

 

 

//2)클래스의 메소드 실행

// car.show();

//실행하려면, 그냥 밖으로 빼서 실행하면 됩니다.

 

 

//3)클래스의 메소드 실행

// System.out.println("메소드 실행 : "  + car.show2()); //

//반면에 return값이 잇다면 또 달라진다.

 

 

car.show();

car.company ="삼성자동차";

System.out.println("car.company : " + car.company);

car.speed = 100;

System.out.println("car.speed : " + car.speed);

System.out.println();

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

//붕어빵2번과 붕어빵1번 내용이 같다.

System.out.println("붕어빵2번");

System.out.println("car1.company : "  + car1.company);

System.out.println("car1.model : "  + car1.model);

System.out.println("car1.color : "  + car1.color);

System.out.println("car1.maxSpeed : "  + car1.maxSpeed);

System.out.println("car1.speed : "  + car1.speed);

 

 

}









★힙(객체 뱃속)에서 만들어진다.

-현대자동차

-그랜저

-검정

-300

-0

 

★show()라는 주소는 힙 객체에 있고, 그것을 따라가면 ★데이터영역에 있는 show()메소드로 간다.



Car2



//Car와 Car2의 클래스의 차이가, 생성자에서도 변수의 값을 입력할수있다.

 

//#1. 필드(=멤버변수, 인스턴스 변수)//객체 뱃속에 들어가는 변수, 객체가 만들어져야 쓸수있다.

String company = "현대자동차";

String model;

String color;

int speed;

 

 

 

//#2. 생성자

public Car2() { // 초기화 내용, 유효성 검사, 없을 시는 생략

//super();

model = "그랜저"; //  String company = "현대자동차";이것과 같은 개념이다. 생성자에 넣을수있다. 대부분 안넣을뿐이다.

color = "빨강";

 

//생성자안에는 super(); = 부모의 기본생성자를 호출하라 이것이 '생략'되어있다.

 

 

}

 

 

 

 

//#3. 메소드



Car2의 메인

public static void main(String[] args) {

//#1. Car2 객체를 생성 - 객체(인스턴스) = Car2로 만든 것을 인스턴스라 한다.

// Car2 myCar;

// myCar = new Car2();

 

Car2 myCar2 = new Car2();

 

System.out.println("myCar2.company" + myCar2.company);

System.out.println("myCar2.model" + myCar2.model);

System.out.println("myCar2.color" + myCar2.color);

System.out.println("myCar2.speed" + myCar2.speed);

 

 

 

}









데이터영역 스택

 

Car클래스 myCar(주소값) company(현대자동차)

model(그랜저)

color(검정)

maxSpeed(300)

 

 

myCar.company

myCar.model

myCar.color

myCar.maxSpeed



필드는 객체 뱃속에, 객체는 힙★ 

지역변수는 스택★

 

클래스의메소드는 힙에다가 (데이터영역)주소가 있고 ,스택영역에서 그 메소드 실행을 하면,

클래스의 메소드로 들어온다.




Student 

 

//#1.필드

String name;

int age;

int score;

 

//#2.생성자

public Student() {

 

}

//#3.메소드



Student 의 메인

public static void main(String[] args) {

//#1. Student 객체 생성

//1-1. 홍길동 객체 생성

Student hong = new Student();

hong.name = "홍길동";

hong.age = 20;

hong.score = 70;

 

//1-2. 김자바 객체 생성

Student kim = new Student();

kim.name = "김자바";

kim.age = 25;

kim.score = 90;

 

//2.출력

//2-1 홍길동 자료 출력

System.out.println("이름 : " + hong.name);

System.out.println("나이 : " + hong.age);

System.out.println("점수 : " + hong.score);

 

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

//2-2 김자바 자료 출력

System.out.println("이름 : " + kim.name);

System.out.println("나이 : " + kim.age);

System.out.println("점수 : " + kim.score);

}






Student2

 

//#1. 필드

String name;

int age;

int score;

 

 

 

 

//#2. 생성자

//이름같고 매개변수가 다르면,서로다른매소드로 인식한다.

public Student2() {} //기본생성자 //생성자 오버로딩 (이름 똑같이하고 여러개 생성하는것)

//이름같고 매개변수 타입이 다른것이거나

//이름같고 매개변수 개수가 다른것이여야 한다.

//기본 생성자는 다른 생성자가 하나라도 있으면

//컴파일러가 자동으로 만들지 않기 때문에

//기본생성자는 생략하면 안됨

 

 

 

public Student2(String name, int age, int score ) { //무엇을 넘겨받을지, 명확하게 하자.

//생성자를 만들면서 재료를 집어넣고 싶을때, 이렇게 사용한다.

 

// name= name;//지역변수에다가 지역변수를 담는 상황

// age = age;//지역변수에다가 지역변수를 담는 상황

// score = score;//지역변수에다가 지역변수를 담는 상황

 

//컴퓨터는 중괄호 블록안에, 필드이름, 메소드이름이 같으면,

//컴퓨터는 자기랑 가까이 있는 중블록 지역변수 이름을 쓴다.

//필드랑 지역변수를 구분해줘야한다.

 

this.name = name; //this - 자신의 객체

//this.name : 필드

this.age = age;

this.score = score;

//this를 사용하는 것은 필드와 구분하려 붙인다.

//구분을 할수있다면, this를 생략할수있다. 되도록이면 this를 써주면 좋다.

 

 

//() 지역변수, 저위에는 필드(인스턴스(객체)필드)

//객체가 만들어지는 시점에 함께 만들어진다.

//객체가 없다면, 저 필드도 의미가없다.

 

 

}

 

//#3. 메소드






//컴퓨터는 중괄호 블록안에, 필드이름, 메소드이름이 같으면,

//컴퓨터는 자기랑 가까이 있는 중블록 지역변수 이름을 쓴다.

//필드랑 지역변수를 구분해줘야한다.



Student2

 

생성자도 오버로딩이 되는구나.




중복을 뽑아내는 것은

★유지보수 좋고, 오류가 적다.

배열 > 메소드 > 클래스 

 

Student3



//#1. 필드

String name;

int age;

int score;

 

//this : 자신의 객체

//this를 사용할때, 반드시 가장 첫줄에 있어야 한다.

//생성자를 호출한다음에 뭔가를 할수가있다.

 

//this();

//1)생성자안에서만 쓸수있다.

//2)생성자에 가장 첫줄에 써야한다.

 

//this.name

//1)필드와 지역변수를 구분하기 위해

 

 

 

//#2. 생성자가 많은 경우 (변경 후)

public Student3() {

//this(); 자신 객체의 생성자 호출

this("홍길동",25,85);

}

public Student3(int score) {

this("김자바",25,score);

}

 

public Student3(String name, int score) {

this(name,25,score);

}

public Student3(String name, int age, int score ) { //무엇을 넘겨받을지, 명확하게 하자.

 

 

this.name = name; //this - 자신의 객체

//this.name : 필드

this.age = age;

this.score = score;

}

 

 

 

 

 

/*

//#2. 생성자가 많은 경우 (변경 전)

 

public Student3() {

name = "홍길동";

age = 20;

score = 85;

}

public Student3(int score) {

name="김자바";

age= 25;

this.score = score;

 

}

 

public Student3(String name, int score) {

this.name=name;

age= 25;

this.score = score;

 

}

public Student3(String name, int age, int score ) { //무엇을 넘겨받을지, 명확하게 하자.

 

this.name = name; //this - 자신의 객체

//this.name : 필드

this.age = age;

this.score = score;

}

*/

//#3. 메소드



Student2,3 의 메인

public static void main(String[] args) {

 

 

 

 

//#1. Student2 객체 생성

// Student2 hong;

// hong = new Student2("홍길동", 20, 95);

Student2 hong = new Student2("홍길동", 20, 95); //위에꺼랑 같다.

Student2 kim = new Student2("김자바", 25, 85); //위에꺼랑 같다.

 

//2.출력

//2-1 홍길동 자료 출력

System.out.println("이름 : " + hong.name);

System.out.println("나이 : " + hong.age);

System.out.println("점수 : " + hong.score);

 

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

//2-2 김자바 자료 출력

System.out.println("이름 : " + kim.name);

System.out.println("나이 : " + kim.age);

System.out.println("점수 : " + kim.score);

 

//결과값은 같다.

 

// Student2 park = new Student2(); //기본 생성자는 생략하면,만들어지지만, 생성자가 1개라도 있을때, 기본생성자 안만든다.

//그래서 이것은 매개변수가 생성되는 생성자가 없어서 에러가 발생했다.

 

 

//#1. Student3 객체 생성

Student3 park = new Student3();

Student3 kim1 = new Student3(85);

Student3 han = new Student3("한사랑",95);

Student3 im = new Student3("임바다",23,85);

 

System.out.println("park.name : " + park.name);

System.out.println("kim1.name : " + kim1.name);

System.out.println("han.name : " + han.name);

System.out.println("im.name : " + im.name);

}






ㅡㅡㅡ

 

7.생성자(Constructor)

-생성자의 특징

클래스의 이름과 동일

반환(리턴) 타입이 없음

 

-생성자의 중요 특징

객체 생성 및 필드 초기화

 

-모든 클래스는 생성자를 반드시 포함해야함

생성자를 정의하지 않으면 컴파일러가 컴파일시 기본생성자를 자동으로 추가

 

-기본생성자 : 입력받을 매개변수(=파라미터)가 없는 생성자

 

8.this 키워드와 this() 메소드

1)this : 자신이 속한 클래스의 객체

생략하면 컴파일러가 컴파일시 자동으로 this.을  붙여 처리

지역변수와 필드명이 구분이 어렵거나, 명확하게 필드임을 나타내고자 할

 경우

this.필드명으로 this를 붙여 필드임을 알려줌

 

2)this() 메소드 : 자기 클래스 내부의 다른 생성자를 호출

this()메소드는 생성자 내부에서만 사용 가능

반드시 중괄호 ({}) 안의 첫 줄에 사용해야 함

생성자의 중복성을 제거하기 위해 사용



 

 






Car

 

지역변수 - 블록을 벗어나는 순간 메모리에서 사라진다.

필드는 1)인스턴스변수  - 객체뱃속에 들어간다.객체만들기전에 메모리상에 존재하지 않는다.

 

2)스타틱변수



public class Car {

String model;

String color;

int speed;

 

 

public Car(){

/*

this.model = "그랜져";

this.color = "노랑";

this.speed = 20;

*/

this("그랜저", "노랑", 20);

 

}

public Car(String model){

/*

this.model = model;

this.color = "노랑";

this.speed = 20;

*/

this(model,"노랑");

}

 

 

public Car(String model, String color, int speed) {

this.model = model;

this.color = color;

this.speed = speed;

 

}

 

public Car(String model, String color) {

this.model = model;

this.color = color;

}

 

 

//생성자를 찾아가서, 문자문자정수형 찾아서 매개변수를 입력해라.

//갯수에 맞는, 생성자를 찾아 호출한다.

}





Car의 메인

public static void main(String[] args) {

Car myCar = new Car(); //1

Car car = new Car("아우디"); //2

Car thisCar = new Car("아반떼", "파랑", 250);

 

 

 

 

 

}

 




Calculator

 

 

//#1. 필드(=인스턴스 변수, 멤버변수)

int num;

 

 

 

//#2. 생성자 (객체를 초기화)

 

 

//#3. 메소드

//[접근 지정자] 리턴타입 메소드(매개변수,...) = (메소드의시그니처)

//{실행문장} = 바디

//[접근 지정자] 리턴타입 메소드(매개변수,...){실행문장}

public void powerOn() { // public(접근 지정자) 생략하면 디폴트

System.out.println("전원을 켭니다.");

}

 

int plus (int x, int y) {

int result = x + y;

return result;

}

 

 

public double divide(int x, int y) {

double result = (double)x / (double)y ;

return result;

}

 

public void powerOff() {

num = 30;

System.out.println(this.num + "입니다");

System.out.println("전원을 끕니다.");

}

 

//#static을 붙이지 않는 이유

//기본적으로 static을 붙였다. 메소드를 만들때,

//static붙은거에서 뭔가를 부를려면, 불림받는 녀석도 static붙어야한다.

//그러나 클래스는, 불르는 것이 아니라, 기능만 만들고 있기 때문에 static을 붙이지 않는다.

 

public void showInfo() {

int testResult = plus(10, 20) + 30;

System.out.println(testResult);

 

System.out.println(divide(5, 7));

 

}

 

//메소드는 자기자신 안에서 자기자신을 호출할수있다.

//메인메소드에서 계쏙 메소드 호출해서 호출한 것처럼 쓸수 있다.

//static 안붙여도 된다. 클래스안에서 static이 없기 떄문이다.




Calculator의 메인

 

//#1. 객체 생성

Calculator cal = new Calculator();

 

cal.powerOn();

 

int result = cal.plus(5, 6);

System.out.println("결과1 : " + result);

 

 

}

 

//설계도가 메모리 영역에 올라와있다.

//메소드는 공유한다. 나머지는 각각의 뱃속에

//메소드는 하나의 영역에 올려놓고 같이 공유해서 쓴다.


'1. JAVA > 3). 자바_개념' 카테고리의 다른 글

자바_개념_Day_16  (0) 2024.01.22
자바_개념_Day_15  (0) 2024.01.19
자바_개념_Day_13  (0) 2024.01.17
자바_개념_Day_12  (0) 2024.01.16
자바_개념_Day_11  (0) 2024.01.15