[Java] 노트정리 : 상속성, overRide, 추상클래스(추상메소드), 인터페이스

Young eee·2023년 1월 2일

Java

목록 보기
18/22
post-thumbnail

📖 상속성

  • 상속성(inheritance) : 부모클래스에서 자식클래스로 처리(method)들과 특성(property)을 물려받은 것

💻 상속성 Ex.

MainClass

import cls.ChildClass;
import cls.ParentClass;

public class MainClass {
	public static void main(String[] args) {
    
		//생성자 부모클래스 먼저 호출됨
		ChildClass cc = new ChildClass('A');
		
		cc.parent_method();
		cc.func();
		cc.name = "홍길동";
		
		//호출안됨
		//cc.number = 12;
		
		ParentClass pc = new ParentClass('B');
		pc.parent_method();
		
	}
}

ParentClass

public class ParentClass {
	
	public String name;
	public char ch;
	protected int number;	//protected : 자식클래스에서 접근허용. 외부에서 접근을 차단
	/*
	public ParentClass() {
		System.out.println("ParentClass ParentClass()");
	}
	*/
	public ParentClass(char ch) {
		System.out.println("ParentClass ParentClass(char ch)");
		this.ch = ch;
	}
	
	public void parent_method() {
		System.out.println("ParentClass parent_method()");
	}
}

ChildClass

public class ChildClass extends ParentClass {
	
	/*
		this : 자기참조(heap 영역의 주소)
	 	super : 부모참조(heap 영역의 주소) keyword
		
		OverRide

	 */
	public ChildClass() {
		super('A');
		System.out.println("ChildClass ChildClass()");
	}
	
	public ChildClass(char c) {
		super(c);
		System.out.println("ChildClass ChildClass(char c)");
	}
	
	public void func() {
		number = 123;
		System.out.println("ChildClass func()");
	}
}

💡 부모함수로 묶어서 자식함수 관리 가능

Ex.

	public static void main(String[] args) {	
    
		//부모클래스 부모클래스객체 = new 자식클래스();
		Parent pobj = new Child();
		pobj.method();	
	}

}
class Parent {
	protected String name;	// 자식클래스에서만 접근을 허용
	
	public Parent() {
		System.out.println("Parent Parent()");
	}
	
	public Parent(String name) {
		this();
		System.out.println("Parent Parent(String name)");
	}
	
	public void pMethod() {
		System.out.println("Parent pMethod()");
	}
	
	public void method() {
		System.out.println("Parent method()");
	}
}

class Child extends Parent {
	public Child() {
		super("성춘향");
		System.out.println("Child Child()");
	}
	
	public void func() {
		name = "홍길동";
	}
	// OverRide : 상속받은 함수를 자식클래스에서 고쳐서 기입하는 것. 조건 -> 같은 사양(prototype)
	public void method() {
		super.method();
		System.out.println("Child method()");
	}
	
	public void process() {
		super.method();	// 부모 클래스 메소드
		this.method(); // 자식 클래스 메소드
	}
}

📌 OverRide

  • 하나의 클래스로 관리함

💻 overRide Ex.

public class MainClass {

	public static void main(String[] args) {
		
        //개별클래스로 관리
		ChildOne pitcher[] = new ChildOne[3];	// child101, child102, child103
		ChildTwo batter[] = new ChildTwo[3];
		
		
		// logic
		//하나의 부모 클래스에 관련 자식클래스를 한번에 저장
		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();
		}
		
		// 하나의 부모클래스로 관리하다가 자식클래스를 꺼내야 할 때 사용 -> 자식클래스 안에 함수를 사용해야 할 때
		ChildOne one = (ChildOne)parent[0];
		one.func();
		
		//instanceof -> keyword
		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 + "]은 ChildTwo으로 생성되었습니다");
			}
		}
			
	}

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

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

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

💻 overRide(활용) Ex.

Mainclass

public class MainClass {

	public static void main(String[] args) {
		/* 
			
			OverRide를 하는 이유 : 하나의 클래스로 관리하기 위함
		
		*/
		
		ChildOne pitcher[] = new ChildOne[3];	// child101, child102, child103
		ChildTwo batter[] = new ChildTwo[3];
		
		// 추가 -> 입력
		// 어느쪽 클래스를 추가?
		
		// logic
		
		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();
		}
		
		// 하나의 부모클래스로 관리하다가 자식클래스를 꺼내야 할 때 사용 -> 자식클래스 안에 함수를 사용해야 할 때
		ChildOne one = (ChildOne)parent[0];
		one.func();
		
		//instanceof -> keyword
		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 + "]은 ChildTwo으로 생성되었습니다");
			}
		}
			
	}

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

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

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

Human

package cls;

public class Human {
	private String name;
	private int age;
	
	public Human() {
	
	}

	public Human(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
	
	@Override
	public String toString() {
		return "name=" + name + ", age=" + age;
	}
}

Batter

package cls;

public class Batter extends Human{
	int batCount;
	int hit;
	
	public Batter() {
		
	}
	public Batter(String name, int age, int batCount, int hit) {
		super(name, age);
		this.batCount = batCount;
		this.hit = hit;
	}
	public int getBatCount() {
		return batCount;
	}
	public void setBatCount(int batCount) {
		this.batCount = batCount;
	}
	public int getHit() {
		return hit;
	}
	public void setHit(int hit) {
		this.hit = hit;
	}
	@Override
	public String toString() {
		return "Batter [" + super.toString() + ", batCount=" + batCount + ", hit=" + hit + "]";
	}
	
}

Pitcher

package cls;

public class Pitcher extends Human{
	private int win;
	private int lose;
	
	public Pitcher() {
	
	}

	public Pitcher(String name, int age, int win, int lose) {
		super(name, age);
		this.win = win;
		this.lose = lose;
	}

	public int getWin() {
		return win;
	}

	public void setWin(int win) {
		this.win = win;
	}

	public int getLose() {
		return lose;
	}

	public void setLose(int lose) {
		this.lose = lose;
	}

	@Override
	public String toString() {
		return "Pitcher [" + super.toString() + ", win=" + win + ", lose=" + lose + "]";
	}
	
}

📖 추상클래스(abstract class)

  • abstract class(추상클래스) : 추상 메소드를 하나 이상 포함하고 있는 클래스
  • 추상 메소드 : 내용(소스코드)는 없고 선언만 되어있는 함수

💻 추상클래스 EX.

public class MainClass {

	public static void main(String[] args) {
		/*
				  일반 메소드
				  public void method(int n) {
				  	처리(코드)
				  }
				  
				  추상 메소드
				  public abstract void method(int n);
		 */
		
		// AbstractClass acls = new AbstractClass();
		Child ch = new Child();
		ch.normalMethod();
		ch.abstractMethod();
        
		// 자식클래스에 상속 후 사용
		AbstractClass acls = new Child();
		acls.normalMethod();
		acls.abstractMethod();
		
		// 자식클래스에 상속하지 않고 바로 정의해서 사용하고 싶을 때
		AbstractClass bcls = new AbstractClass() {
			
			@Override
			public void abstractMethod() {
				System.out.println("AbstractClass abstractMethod");
				
			}
		};
		bcls.normalMethod();
		bcls.abstractMethod();
	}

}

abstract class AbstractClass  {
	
	private String name;
	
	// 일반 메소드
	public void normalMethod() {
		System.out.println("AstractClass normalMethode()");
	}
	
	// 추상 메소드
	public abstract void abstractMethod();
}

class Child extends AbstractClass {
	//Source -> Override/Implement Methods...
	@Override
	public void abstractMethod() {
		System.out.println("Child abstractMethod");
		
	}
	
}

📖 인터페이스(Interface)

  • 추상메소드만을 포함하는 class == 껍데기(통)
  • 선언할 때, prototype을 확인하는 경우에 사용
  • 다중 상속이 가능
  • 확장성, 클래스에서 포함하는 메소드를 파악하는데 유리

💻 인터페이스 Ex.

MainClass

public class MainClass {

	public static void main(String[] args) {
		MyClass mycls = new MyClass();
		mycls.func();
		
		MyInterface myint = new MyClass();
		myint.func();
		
		MyInterface myif = new MyInterface() {
			
			@Override
			public void func() {
				System.out.println("MyInterface func()");
				
			}
		};
		
		myif.func();
		
		Calculator cal = new Calculatorimpl();
		cal.plus();
		cal.minus();
	}

}

interface MyInterface {

//	private int number;		// 변수선언 불가
//	public void method() {} // 메소드 작성 불가
	
	public void func();
}

class MyClass implements MyInterface {

	@Override
	public void func() {
		System.out.println("MyClass func()");
		
	}
	
}

Calculator Interface

public interface Calculator {
	public void plus();
	public void minus();
}

Calculatorimpl Class

// class를 생성할 때 interface를 선택해서 생성하면 자동으로 생김
public class Calculatorimpl implements Calculator {

	@Override
	public void plus() {
		System.out.println("CalculatorImpl plus()");

	}

	@Override
	public void minus() {
		System.out.println("CalculatorImpl minus()");

	}

}

0개의 댓글