객체 = 사람이 말로 표현할 수 있는 모든 것
객체는 속성과 행위로 이루어져 있다.
속성은 변수, 행위는 메서드
프로그램에서 필요한 변수와 메서드를 뽑는 것이 추상화과정이다.
이 과정이 끝나면 나오는 결과물이 Class다
메소드의 종류
일반정의 메소드 | 생성자 |
생성자
역할 : 실제 메모리를 할당해주고 변수가 그 메모리를 가르키게 해놓은것 (메모리 세팅)
생성자의 특징
- 클래스 이름과 동일한 형태의 메소드
- 하나의 클래스가 여러개의 생성자를 가질 수 있다.
- 생성자 = 메소드 즉, 오버로딩 가능
- 리턴 타입이 없다.
- 접근제한자가 private와 public만 가능하다. 일반적으로 public만 사용한다.
- 클래스가 만들어질때 자동으로 ( 안보이는 )Default 생성자가 만들어진다.
ex) public class MainClass(){} 이런식으로 만들어진 클래스에 public MainClass(){}가 만들어짐 - Default생성자는 사용자가 생성자를 선언하면 사라짐. 하지만 오버로딩이 가능하기에 작성하면 사용가능하다.
생성자를 한눈에 알아보는법
- 데이터타입이 붙지 않는다.
- 메소드나 변수는 첫글자가 소문자로 시작해야함 ( 코딩 컨벤션 ) 그러나 생성자는 클래스 이름과 같아야하므로 첫글자가 대문자
오버로딩 & 오버라이딩
오버로딩 - 하나의 클래스 안에서 같은 메소드(or 생성자)이름으로 정의가 가능하다. 오버로딩의 조건은 다음과 같다.
- 메소드의 이름이 같아야한다.
- 매개변수의 개수나 타입이 달라야한다.
- 리턴값만 다른것은 오버로딩 불가능
<예시>
public int xxx(){}
public char xxx(){} // int xxx()와 같이있을때 매개변수가 다르지 않으므로 오류
public char xxx(int y){}
public char xxx(int a, int b){}
public int xxx(int x, int y){} // 위의 char xxx(int a, int b)와 매개변수 개수와 형태가 같으므로 오류
오버라이딩 - 상속관계에 있어 부모클래스에 있는 메소드를 자식클래스에서 다시 사용할 수 있게 재정의 한다.
- 오버라이딩하고자 하는 메소드의 이름, 매개변수, 리턴값이 모두 같아야한다.
- 선언부가 부모의 것과 완벽히 동일해야한다.
참조변수의 변화
package com.java.ex.character;
public class warrior { //import시킬 Warrior Class
private String name;
private int hp;
private int mp;
private int str;
private int intell;
private int agil;
private int level;
public warrior(String name, int hp, int mp, int str, int intell, int agil, int level) {
this.name = name;
this.hp = hp;
this.mp = mp;
this.str = str;
this.intell = intell;
this.agil = agil;
this.level = level;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getHp() {
return hp;
}
public void setHp(int hp) {
this.hp = hp;
}
public int getMp() {
return mp;
}
public void setMp(int mp) {
this.mp = mp;
}
public int getStr() {
return str;
}
public void setStr(int str) {
this.str = str;
}
public int getIntell() {
return intell;
}
public void setIntell(int intell) {
this.intell = intell;
}
public int getAgil() {
return agil;
}
public void setAgil(int agil) {
this.agil = agil;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
}
package com.java.ex.main;
import com.java.ex.character.Warrior;
public class Main
{
public static void main(String[] args) {
Warrior w1 = new Warrior();
Warrior w2 = new Warrior("전사1",100,100,100,50,70,3);
System.out.println("이름 : " + w2.getName());
w1 = w2;
System.out.println("이름 : " + w1.getName());
w1.setName("전사2");
System.out.println("이름 : " + w1.getName());
System.out.println("이름 : " + w2.getName()); // 참조변수니까 한번에 바뀐다
}
}
위의 결과는 어떻게 될까?
답은
이름 : 전사1
이름 : 전사1
이름 : 전사2
이름 : 전사2
패턴디자인
반복되는 설계란 뜻이다.
패턴이란?
- 객체지향 언어의 장점들을 모아 가장 효율적으로 개발을 할 수 있게 만들어놓은 틀
- 반복적인 형태
싱글톤 패턴
- 오류를 줄여주는 패턴
- 클래스의 인스턴스는 오직 하나임을 보장
- 인스턴스에 접근할 수 있는 전역적인 접촉점을 제공
ex) 서버1, 서버2, 서버3이 있을때 서버2가 서버시간을 (서머타임같은걸로 인해)바꿨을시 서버 1, 3의 시간도 변경해줌 - 메모리 낭비가 적어짐 - 인스턴스에 접근하는 클래스 하나만 고정해서 공유하고 사용함 = new를 한번만씀
package com.java.ex;
public class SingletonClass {
private static SingletonClassSINGLETON_CLASS_INSTANCE= new SingletonClass(); // 싱글톤 하나만 고정해서 공유하고 쓸거임
private int i=10;
private SingletonClass(){ // default생성자가 아님 왜? private가 붙어서 디폴트 생성자는 public임
}
public static SingletonClass getSingletonClass(){ // static이 붙어있으니까 클래스이름.getSingletonClass로 가야함
if(SINGLETON_CLASS_INSTANCE== null){// 잘못적었을까봐 혹시몰라서 찍어줌
SINGLETON_CLASS_INSTANCE= new SingletonClass();
}
returnSINGLETON_CLASS_INSTANCE;
}
public int getI(){
return i;
}
public void setI(int i){
this.i = i;
}
}
package com.java.ex;
public class FirstClass {
public FirstClass() {
SingletonClass sgtClass = SingletonClass.getSingletonClass();
System.out.println("Firstlass");
System.out.println("i = " + sgtClass.getI());
sgtClass.setI(200);
System.out.println("i = " + sgtClass.getI());
}
}
public class SecondClass {
public SecondClass(){
SingletonClass sgtClass = SingletonClass.getSingletonClass();
System.out.println("SecondClass");
System.out.println("i = " + sgtClass.getI());
}
}
public class Main {
public static void main(String[] args) {
FirstClass fc = new FirstClass();
SecondClass sc = new SecondClass();
}
}
Static(정적변수)
키워드 자체가 스태틱 변수가 나오면 변수를 객체변수가 아니라 클래스 변수로 설정해준다.
ex) 위의 warrior에서 static name(){}이런식으로 만들어져있고 hp, mp등이 구현되어있다고 봤을때 name은 고정되어있고 객체마다 다른값의 hp, mp값을 넣을 수 있다.
'실력 향상 일지 > 23년 1학기 정리' 카테고리의 다른 글
[수리능력(통계)] 분포와 편포 (2) | 2023.04.17 |
---|---|
[수리능력(통계)] 표본의 추출 (0) | 2023.04.13 |
[Java] 3월 정리 - 1 (0) | 2023.03.31 |