organize/자바

Java 10

001cloudid 2024. 4. 22. 14:16
728x90

상속(Inheritance)

기존 클래스로 새로운 클래스를 작성하는 것(코드의 재사용)
두 클래스를 부모와 자식으로 관계를 맺어주는 것
class 자식클래스 extends 부모클래스{ //... }
class Parent{}
class Child extends Parent{ //...}
자손은 조상의 모든 멤버를 상속받음(생성자, 초기화블럭 제외)
자손의 멤버 개수는 조상보다 적을 수 없음(같거나 많음)
자손의 변경은 조상에 영향을 미치지 않음
상속을 자손은 하면 점점 확장됨

 

package chapter07;

class TV{
	boolean power; //전원상태(on/off)
	int channel; //채널
	
	void power() {
		power = !power;
	}
	void channelUp() {
		++channel;
	}
	void channelDown() {
		--channel;
	}
	//부모 멤버 5개
}

class SmartTV extends TV{ //SmartTV는 TV에 자막을 보여주는 기능
	boolean caption; //자막상태(on/off)
	void displayCation(String text) {
		if(caption) { //자막 상태가 on(true)일 때 text를 보여줌
			System.out.println(text);
		}
	}
	//자식 멤버 2개
}
public class Study01Ex1 {

	public static void main(String[] args) {

		SmartTV smartTV = new SmartTV();
		smartTV.channel = 10; //조상 클래스로부터 상속받은 멤버
		smartTV.channelUp(); //조상 클래스로부터 상속받은 멤버
		System.out.println(smartTV.channel);
		smartTV.displayCation("Hello World");
		smartTV.caption = true;
		smartTV.displayCation("Hello world");
		
		
	}

}

 

클래스 간의 관계

포함 관계
포함(composite)? 클래스의 멤버 변수로 참조변수를 선언하는 것
작은 단위의 클래스를 만들고 이들을 조합해서 클래스를 만듦

클래스 간의 관계 결정하기
상속관계 : ~은 ~이다. (is-a) 10% 꼭 필요할 때만
포함관계 : ~은 ~를 가지고 있다. (has-a) 90%

 

package chapter07;

class Point{
	int x;
	int y;
}

class Circle{
	int x; //원점의 x좌표
	int y; //원점의 y좌표
	int r; //반지름
}

class CircleInheritance extends Point{
	int r;
}

class CircleComposite{
	Point c = new Point(); //원점
	int r;
}

public class Study02Ex1 {

	public static void main(String[] args) {
		
		//상속
		CircleInheritance circleInheritance = new CircleInheritance();
		circleInheritance.x = 1;
		circleInheritance.y = 2;
		circleInheritance.r = 3;
		System.out.println("circleInheritance.x = " + circleInheritance.x);
		System.out.println("circleInheritance.y = " + circleInheritance.y);
		System.out.println("circleInheritance.r = " + circleInheritance.r);
		System.out.println();
		
		//포함
		CircleComposite circleComposite = new CircleComposite();
		circleComposite.c.x = 10;
		circleComposite.c.y = 20;
		circleComposite.r = 30;
		System.out.println("circleComposite.c.x = "+circleComposite.c.x);
		System.out.println("circleComposite.c.y = "+circleComposite.c.y);
		System.out.println("circleComposite.r = "+circleComposite.r);
		
		
	}

}

 

단일 상속(Single Inheritance)

하나의 부모만 상속 가능(인터페이스를 통해 다중 상속 문제를 해결)
비중이 높은 클래스 하나만 상속관계로, 나머지는 포함 관계(Study03Ex1)

Object 클래스 모든 클래스의 조상
부모가 없는 클래스는 자동적으로 Object 클래스를 상속받게 됨
모든 클래스는 Object 클래스에 정의된 11개의 메서드를 상속(toString(), equals(Object obj), hashCode(),...)
println() -> 참조변수 -> toString()호출
System.out.println(참조변수.toString()); == System.out.println(참조변수);

 

package chapter07;

class TV1{
	boolean power;
	int channel;
	
	void power() {
		power = !power;
	}
	void channelUp() {
		++channel;
	}
	void channelDown() {
		--channel;
	}
}

class DVD{
	boolean power;
	
	void power() {
		power = !power;
	}
	void play() {}
	void stop() {}
	void rew() {}
	void ff() {}
}

class TvDVD extends TV1{
	DVD dvd = new DVD();
	
	void play() {
		dvd.play();
	}
	
	void stop() {
		dvd.stop();
	}
	
	void rew() {
		dvd.rew();
	}
	
	void ff() {
		dvd.ff();
	}
	
}

public class Study03Ex1 {

}

 

오버라이딩(Overriding)

상속받은 조상의 메서드를 자신에 맞게 변경하는 것

오버라이딩 조건
1. 선언부가 조상 클래스의 메서드와 일치(반환타입, 메서드 이름, 매개변수목록)
2. 접근 제어자를 조상 클래스의 메서드보다 좁은 범위로 변경할 수 없음
3. 예외는 조상 클래스의 메서드보다 많이 선언할 수 없음(같거나 작아야함)

오버로딩, 오버라이딩(Study04Ex3)
오버로딩 : 기존에 없는 새로운 이름이 같은 메서드를 정의하는 것(new)
오버라이딩 : 상속받은 메서드의 내용을 변경하는 것(change, modify)

 

package chapter07;

class PointS4E1{
	int x;
	int y;
	
	String getLocation() {
		return "x : " + x + ", y = " + y;
	}
}

class Point3DS4E1 extends PointS4E1{
	int z;
	
	//조상(getLocation()) 오버라이딩
	String getLocation() {
		return "x : " + x + ", y = " + y + ", z = " + z;
	} //선언부 변경 불가. 내용(구현부)만 변경 가능 
	
}

public class Study04Ex1 {
	
	public static void main(String[] args) {

		Point3DS4E1 point3ds4e1 = new Point3DS4E1();
		point3ds4e1.x = 3;
		point3ds4e1.y = 4;
		point3ds4e1.z = 5;
		System.out.println(point3ds4e1.getLocation());
		
	}

}

 

package chapter07;

//Study04Ex1.java 간단하게 리팩토링

class PointS4E2{
	int x;
	int y;
	
	public PointS4E2(int x, int y) {
		this.x = x;
		this.y = y;
	}
	
	//Object 클래스의 toString()을 오버라이딩
	public String toString() {
		return "x : " + x + ", y = " + y;
	}
}

public class Study04Ex2 {
	
	public static void main(String[] args) {

//		PointS4E2 pointS4E2 = new PointS4E2();
		PointS4E2 pointS4E2 = new PointS4E2(5,6);
//		pointS4E2.x = 3;
//		pointS4E2.y = 4;
//		System.out.println("pointS4E2.toString() = "+pointS4E2.toString());
		System.out.println("pointS4E2 = "+pointS4E2);
		
	}

}

 

package chapter07;

class ParentS4E3{
	void parentMethod() {}
}

class ChildS4E3 extends ParentS4E3{
	void parentMethod() {} //오버라이딩
	void parentMethod(int i) {} //오버로딩
	
	void childMethod() {} //메소드 정의
	void childMethod(int i ) {} //오버로딩
//	void childMethod() {} //중복정의. 에러
}

public class Study04Ex3 {

}

 

super

this와 비슷
객체 자신을 가리키는 참조변수. 인스턴스 메서드(생성자)내에만 존재(static 메서드 내에 사용불가)
조상의 멤버를 자신의 멤버와 구분할 때 사용

 

package chapter07;

class ParentS5E1{
	int x = 10; //super.x
}

class ChildS5E1 extends ParentS5E1{
	int x = 20; //this.x
	
	void showInfo() {
		System.out.println("x = " + x);
		System.out.println("this.x = " + this.x);
		System.out.println("super.x = " + super.x);
	}
}

public class Study05Ex1 {

	public static void main(String[] args) {

		ChildS5E1 childS5E1 = new ChildS5E1();
		childS5E1.showInfo();
		
	}
	
}

 

package chapter07;

class ParentS5E2{
	int x = 10; //super.x와 this.x 둘 다 가능
}

class ChildS5E2 extends ParentS5E2{
	void showInfo() {
		System.out.println("x = " + x);
		System.out.println("this.x = " + this.x);
		System.out.println("super.x = " + super.x);
	}
}

public class Study05Ex2 {

	public static void main(String[] args) {

		ChildS5E2 childS5E2 = new ChildS5E2();
		childS5E2.showInfo();
		
	}
	
}

 

super() 조상의 생성자
조상의 생성자를 호출할 때 사용
조상의 멤버는 조상의 생성자를 호출해서 초기화

 

package chapter07;

class PointS5E3{
	int x, y;
	
	PointS5E3(int x, int y) {
		//iv 초기화
		this.x = x;
		this.y = y;
	}
}

class Point3DS5E3 extends PointS5E3{
	int z;
	
//	모든 생성자는 첫 줄에 다른 생성자를 호출. 따라서 기본 생성자 작성은 필수
//	Point3DS5E3(int x, int y, int z){
//		this.x = x; //조상 멤버 초기화
//		this.y = y; //조상 멤버 초기화
//		this.z = z;
//	}
	
	//자손의 생성자
	Point3DS5E3(int x, int y,int z){
		super(x, y); //조상클래스의 생성자 PointS5E3(int x, int y)를 호출
		this.z = z; //자신의 멤버를 초기화
	}
}




public class Study05Ex3 {

}

 

package chapter07;

class PointS5E4{
	int x;
	int y;
	
	PointS5E4(){
		this(0,0); //OK
	}
	
	PointS5E4(int x, int y){
		//super(); 조상 기본 생성자 호출
		this.x = x;
		this.y = y;
	}
}

public class Study05Ex4 {

}

 

패키지, 클래스 패스

패키지
서로 관련된 클래스의 묶음
클래스는 클래스 파일(*.class), 패키지는 폴더. 하위 패키지는 하위 폴더
클래스의 실제 이름(full name)은 패키지를 포함(java.lang.String)

패키지 선언
패키지는 소스파일의 첫 번째 문장으로 단 한 번 선언
같은 소스 파일의 클래스들은 모두 같은 패키지에 속하게 됨
패키지 선언이 없으면 이름없는 패키지에 속하게 됨

클래스 패스(classpath)
클래스 파일(*.class)의 위치를 알려주는 경로
환경변수 classpath로 관리하며, 경로간의 구분자는 ';'를 사용
classpath(환경변수)에 패키지의 루트를 등록해줘야 함

 

import

클래스를 사용할 때 패키지 이름을 생략할 수 있음
컴파일러에게 클래스가 속한 패키지를 알려줌
ctrl + shift + o
java.lang패키지의 클래스는 import하지 않고도 사용할 수 있음
String, Object, System, Thread,...

import문의 선언
import 패키지명.클래스; 또는 import 패키지명.*;
위치는 패키지문과 클래스 선언 사이에 선언함

static import문
static 멤버를 사용할 때 클래스 이름을 생략할 수 있게 해줌

728x90

'organize > 자바' 카테고리의 다른 글

Java 12  (0) 2024.04.24
Java 11  (0) 2024.04.23
Java 9  (0) 2024.04.21
자바 처음부터 다시 시작하기 8  (1) 2024.04.20
자바 처음부터 다시 시작하기 7  (1) 2024.04.18