[Java] 상속성, 다형성, super, 추상클래스, 인터페이스

수박이삼촌·2024년 1월 22일
0

Java

목록 보기
11/21
post-thumbnail

상속성(inheritance)

12-29

12-29-1



다형성(polymorphism)

package sample29_Polymorphism;

public class MainClass {
	public static void main(String[] args) {
		/*
		 	Polymorphism : 다형성
		 	- 참조 변수의 타입을 자신 또는 상속받는 상위 타입으로 선언
		 	
		 	부모클래스  부모클래스 객체 = new 자식클래스()
		 	데이터타입    instance  =  소속 객체 
		 */
		
	//	Child cobj = new Child();
	//	cobj.pMethod();
	//	cobj.name = ""; -> 원래는 error
		
		/*
		Child cobj = new Child();
		// cobj.method();
		cobj.process();
		*/
		
		/*
		 	부모클래스 부모클래스객체 = new 자식클래스()
		 */
		Parent pobj = new Child();
		pobj.method();
		
		Child c = new Child();
	}
}


class Parent{
	protected String name;	// 자식클래스에서만 접근을 허용
	
	public Parent() {
		System.out.println("Parent Parent()");
	}
	
	public  Parent(String name) {
		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{
	// Parent 클래스 들어옴
	public  Child() {
		// super(); 생략되어 있음
		super("성춘향");
		System.out.println("Child Child()");
	}
	
	public void func() {
		name = "홍길동";
		pMethod(); // 앞에 this가 생략되어 있음.
	}
	
	// OverRide : 상속받은 함수를 자식클래스에서 고쳐 기입하는 것. 같은 사양(prototype)
	public void method() {
		System.out.println("Child method()");
	}
	
	public void process() {
		
		super.method(); // 부모 클래스 메소드
		
		this.method();	// 자식 클래스 메소드
	}
}


Overriding

package sample30;

public class MainClass {

	public static void main(String[] args) {
		// OverRiding(재정의)을 하는 이유 :
		// 하나의 instance로 여러 가지 instance를 관리하기 위한 방법
			
		//	투수, 타자 합쳐서 10명을 뽑아야 한다면?
			ChildOne pitcher[] = new ChildOne[10];	//	child101, child102, child103
			ChildTwo batter[] = new ChildTwo[10];
			
			// 추가 -> 입력
			// 어느쪽 클래스를 추가?
			
			// 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으로 생성되었습니다.");
			}
			
			// parent함수가 어디 소속인지 알 수 있다.
			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("Parent func()");
	}
}

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


super

Main Class

package sample31;

import cls.Batter;
import cls.Human;
import cls.Pitcher;

public class MainClass {
	public static void main(String[] args) {
			
	//	Pitcher pitArr[] = new Pitcher[10];
	//	Batter batArr[] = new Batter[10];
		
	//	OR
		
		Human humanArr[] = new Human[5];	// 원래는 10
		
		humanArr[0] = new Pitcher("성춘향", 16, 10, 2);
		humanArr[1] = new Pitcher("일지매", 22, 6, 3);
		humanArr[2] = new Batter("홍두께", 24, 13, 4);
		humanArr[3] = new Batter("홍길동", 25, 21, 6);
		humanArr[4] = new Pitcher("이몽룡", 17, 9, 1);
		
		for (int i = 0; i < humanArr.length; i++) {
			System.out.println(humanArr[i].toString());
		}
		
		for (int i = 0; i < humanArr.length; i++) {
			
			if(humanArr[i] instanceof Pitcher) {
				Pitcher p =(Pitcher)humanArr[i];	// human 인스턴스배열이 Pitcher 클래스로 생성되었을 때
				System.out.println(p.getName() + " " + p.getWin() + "승 " + p.getLose() + "패");
			}
			else if(humanArr[i] instanceof Batter) {
				Batter b = (Batter)humanArr[i];
				System.out.println(b.getName() + " " +b.getBatCount() + "타수" + b.getHit() + "안타");
			}
		}
		
		// Human 대신 Object로 쓸 수 있음.
		Object h1 = new Pitcher();	
		Object h2 = new Batter();
		
		Object objArr = new ThreeClass();
		NumberInter arrObj = new ThreeClass();

	}
}

interface NumberInter{
}

class OneClass implements NumberInter{
	
}

class TwoClass implements NumberInter{
	
}

class ThreeClass implements NumberInter{
	
}


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 + "]";
	}

}


Human

package cls;

public class Human {	// extends Object 가 생략되어 있는 거임.
	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;
	}
	
}

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(추상 클래스)

package sample32;

public class MainClass {
	public static void main(String[] args) {
		/*
		 	abstract class : 추상 클래스
		 					 추상 메소드를 하나 이상 포함하고 있는 클래스
		 					 단독사용이 아닌, 상속한 클래스를 만들어서 사용을 강제한다.
		 					 일반 메소드, 추상 메소드 둘 다 포함 가능
		 	추상 메소드 : 내용(소스코드)은 없고 선언만 되어 있는 함수
		 				추상 메소드가 하나만 있더라도 해당 클래스는 추상 클래스로 선언해야 함.
		 	
		 	일반 메소드		 
		 	public void method(int n){
		 		처리(코드)
		 	}
		 	
		 	public abstract void method(int n);
		 			
		 */
	//	AbstractClass acls = new AbstractClass(); -> error 내용이 없어서 
		// abstract클래스는 무조건 상속을 받아야 선언됨.
		
		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("ChildClass abstractMethod()");
				
			}
		};
		bcls.normalmethod();
		bcls.abstractMethod();
	}
}

abstract class AbstractClass {

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

class Child extends AbstractClass{

	@Override
	public void abstractMethod() {
		System.out.println("ChildClass abstractMethod()");
		
	}
	
}


final

package sample34_final;

public class MainClass {
	public static void main(String[] args) {
		/*
		 	final : 변수, 클래스, 메소드
		 			== const, define
		 */
		
		final int NUMBER = 1;	// 상수(변경할 수 없는 수), 대입용, 대문자
		// number = 2;
		
		int num = NUMBER;
	}

}

// 클래스 앞에 final : 상속금지
/* final */ class MyClass{
	
	public /* final */ void method() { // Override 금지
		
	}
}

class YouClass extends MyClass{

	@Override
	public void method() {
		method();
	}
	
	
}


Interface

Main Class

package smaple33;

import cal.Calculator;
import cal.CalculatorImp1;

public class MainClass {
	public static void main(String[] args) {
		/*
			interface : 추상메소드만을 포함하는 class    == 껍데기(통)
						선언, prototype를 확인하는 경우
						다중 상속이 가능하다
						확장성, 클래스에서 포함하는 메소드를 파악하는데 유리하다	
						분업할 때 많이 사용. 가짜 로직으로 프로그램 실행시킬 때?  	
			
			abstract와 차이점
			abstract는 클래스 안에 추상 메소드와 함께 일반 메소드도 포함이 가능하지만,
			interface는 클래스 안에 본체가 없는 메소드들만을 포함하여야 한다.
		 */
		
		// MyInterface mi = new MyInterface();
		
		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 CalculatorImp1();
		cal.plus();
		cal.minus();
		
		CalculatorImp1 cali = new CalculatorImp1();
	}

}

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

package cal;

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

Calculator Implement

package cal;

public class CalculatorImp1 implements Calculator {

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

	}

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

	}

}

Java과제.pdf

profile
Today I Learned

0개의 댓글