[JAVA] 객체지향프로그래밍(OOP)의 3요소

seonjeong·2022년 12월 29일
0

Java

목록 보기
10/26
post-thumbnail

💖 은닉성(Encapsulation)

캡슐화. 외부접근 제어(차단, 읽기전용)

접근지정자

  • private : 개인적인 -> 직접적인 접근 불가, getter와 setter를 통해 접근 가능
  • public : 대중적인(누구나) -> 직접적인 접근 가능
  • protected : 상속에 관련

예시

public class MainClass {
	public static void main(String[] args) {
    	MyClass mnumber = 1;ycls = new MyClass();
        
        mycls.number = 1;		  // private -> 외부에서 접근 불가
        mycls.name = "홍길동";		// public -> 외부에서 접근 가능
        mycls.height = 174.1;	  // protected -> 외부에서 접근 불가
    
    	mycls.setNumber(1);		  // setter를 통해 외부에서 값을 설정하고
        mycls.getNumber();		  // getter를 통해 외부에서 값을 반환한다
	}
}

public class myClass {
	// 멤버변슈 90%이상 -> private
	private int number;
	public String name;
	protected double height

	// 메서드 90%이상 -> public
	public void setNumber(int num) {
		this.number = num;
	}

	public int getNumber() {
		return number;
	}
}

💖 상속성(Inheritance)

부모클래스에서 자식클래스로 처리(method)들과 특성(property)을 물려받는 것
protected -> 자식클래스에서 접근 허용. 외부 접근 불가

  • this : 자기참조(heap영역의 주소)
  • super : 부모참조(heap영역의 주소)

형식

class 자식클래스명 extends 부모클래스명 {
	// ...
}

예시

public class MainClass {
	public static void main(String[] args) {
		Child c = new Child();	// 부모생성자가 먼저 자식생성자가 그 후에 생성됨
        
        c.parent_method();
        c.func();
        // c.number = 12; -> 접근 불가
        
        Parent p = new Parent();
        p.parent_method();
        // p.number = 12; -> 접근 불가
    }
}

class Parent {
	public String name;
    public char ch;
    protected int number;
    
    public Parent() {
    	System.out.println("Parent Parent()");
    }
    
    public void parent_method() {
    	System.out.println("Parent parent_method()");
    }
}

class Child extends Parent{
	public Child() {
    	System.out.println("Child Child()");
    }
    
    public void func() {
    	this.number = 123;
        	System.out.println("Child func()");
    }
}

// console
/*
Parent Parent()
Child Child()
Parent parent_method()
Child func()
Parent Parent()
Parent parent_method()
*/

💖 다형성(Polymorphism)

여러 가지 형태를 가질 수 있는 능력
상속을 받아야만 사용가능
자식클래스는 하나의 부모로부터만 상속받을 수 있음
부모클래스 타입의 참조변수로 자식클래스의 인스턴스를 참조할 수 있음 (그 반대는 불가)

  • 자식클래스에는 자식클래스만 담을 수 있음 -> 자식클래스를 따로 관리
  • 부모클래스에는 모든 자식클래스를 담을 수 있음 -> 자식클래스를 모두 관리

형식

부모클래스 부모클래스객체 = new 자식클래스();

예시

public class MainClass {
	public static void main(String[] args) {
    
    	ChildClass cobj = new ChildClass();
        cobj.pMethod();
        
        ParentClass pobj = new ChildClass();
        // ChildClass obj = new ParentClass(); -> 참조불가
        pobj.method();
    }
}

class ParentClass {
	protected String name;
    
    public ParentClass() {
    	System.out.println("ParentClass ParentClass()");
    }
    
    public void pMethod() {
    	System.out.println("ParentClass pMethod()");
    }
    
    public void method() {
    	System.out.println("ParentClass method()");
    }
}

class ChildClass extends ParentClass{
	public ChildClass() {
    	System.out.println("ChildClass ChildClass()");
    }
    
    public void func() {
    	name = "홍길동";
        pMethod();	// -> this.pMethod();
    }
    
    public void process() {
    	super.method();	// 부모클래스 메서드
        this.method();	// 자식클래스 메서드
    }
}

// console
/*
ParentClass ParentClass()
ChildClass ChildClass()
ParentClass pMethod()
ParentClass ParentClass()
ChildClass ChildClass()
ParentClass method()
*/

참조변수의 형변환
: 서로 상속관계에 있는 클래스사이에서만 가능

  • 자식 -> 부모 (업캐스팅, up-casting, 생략가능)
  • 부모 -> 자식 (다운캐스팅, down-casting, 생략불가)

instanceof 연산자
: 참조변수가 참조하고 있는 인스턴스의 실제 타입을 알아보기 위한 연산자
: 주로 조건문에 사용. boolean값을 반환

형식

// 참조변수의 형변환
(변환하고자 하는 타입의 이름)형변환 할 타입

// instanceof 연산자
참조변수 instanceof 클래스명

예시

public class MainClass {
	public static void main(String[] args) {
    
    	// 합해서 5개가 필요할 경우, 각각 5개씩 생성, 관리해야함
    	// ChildOne child1[] = new ChildOne[5]; 
        // ChildTwo child2[] = new ChildTwo[5];
    
    	// 부모요소로 한 번에 5개만 생성
    	Parent parent[] = new Parent[5];
        
        // 하나의 인스턴스로 관리가능
        parent[0] = new ChildOne();
        parent[1] = new ChildTwo();
        parent[2] = new ChildTwo();
        parent[3] = new ChildTwo();
        parent[4] = new ChildOne();
        
        for(int i = 0; i < parent.length; i++) {
        	parent[i].method();
        }
        
        // parent[0].func(); -> 접근 불가. 부모->자식으로 형변환 필요
        ChildOne one = (ChildOne)parent[0];
        one.func(); // -> 접근 가능
        
        // instanceof
        if(parent[0] instanceof ChildOne) {
        	System.out.println("parent[0]는 ChildOne으로 생성되었습니다");
        }
        
        for(int i = 0; i < parent.length; i++) {
        	if(parent[i] instanceof ChildOne) {
        		System.out.println("parent[" + i + "]는 ChildOne으로 생성되었습니다");
        	} else if(parent[i] instanceof ChildTwo) {
            	System.out.println("parent[" + i + "]는 ChildTow으로 생성되었습니다");
            }
        }
    }
}

class Parent {
	public void method() {
    	System.out.println("Parent method()");
    }
}

class ChildOne extends Parent{
	public void method() {
    	// overriding
        System.out.println("ChildOne method()");
    }
    
    public void func() {
    	System.out.println("ChildOne method()");
    }
}

class ChildTwo extends Parent{
	public void method() {
    	// overriding
        System.out.println("ChildTwo method()");
    }
    
    public void process() {
    	System.out.println("ChildTwo method()");
    }
}

// console
/*
ChildOne method()
ChildTwo method()
ChildTwo method()
ChildTwo method()
ChildOne method()
ChildOne method()
parent[0]는 ChildOne으로 생성되었습니다
parent[0]는 ChildOne으로 생성되었습니다
parent[1]는 ChildTow으로 생성되었습니다
parent[2]는 ChildTow으로 생성되었습니다
parent[3]는 ChildTow으로 생성되었습니다
parent[4]는 ChildOne으로 생성되었습니다
*/
profile
🦋개발 공부 기록🦋

0개의 댓글

관련 채용 정보