[개발] - Java/후발대
후발대 9일차 전체 코드
완벽한 장면
2023. 1. 16. 09:29
오버로딩, 오버라이딩, 다형성
public class MathTest {
public int add (int a, int b) {
System.out.println("int add(int a, int b) - " );
return a+b;
}
public int add (int a, int b, int c) {
System.out.println("int add(int a, int b, int c) - " );
return a+b+c;
}
public long add (long a, int b) {
System.out.println("int add(long a, int b) - " );
return a+b;
}
public long add (long a, long b) {
System.out.println("int add(long a, long b) - " );
return a+b;
}
// 배열의 합을 반환하는 메서드
public int add(int[] a) {
System.out.println("int add(int[] a-");
int result=0;
for (int i = 0; i < a.length; i++) {
result += a[i];
}
return result;
}
// 참고
// 가변인수
// 가변 인수를 사용하는 메소드 => 가변 인수는 자료형 뒤에 "..."을 쓰고 배열 이름을 입력하면 된다.
// 가변 인수는 인수 목록의 맨 마지막에 딱 1번만 사용할 수 있다.
public int total(int...numbers){
int result = 0;
for (int i = 0; i < numbers.length; i++) {
result+=numbers[i];
}
return result;
}
}
-----
public class Day08 {
public static void main(String[] args) {
MathTest mt = new MathTest();
// 같은 기능을 실행하는 메소드의 인수가 서로 다를 경우 많은 수의 메소드 오버로딩이 필요하다.
System.out.println("add(3,3) : " + mt.add(3,3));
System.out.println("add(3,3,4) : " + mt.add(3,3,4));
System.out.println("add(3L,3) : " + mt.add(3L,3));
System.out.println("add(3,3L) : " + mt.add(3,3L));
// 메소드 인수를 배열로 구현하면 많은 수의 메소드 오버로딩이 필요가 없지만 인수를 배열로
//선언하고 선언한 배열에 초기치를
// 지정해서 호출되는 메소드로 전달해야 하는 번거로움이 있다.
System.out.println("add(1,2,3) :" + mt.add(new int[] {1,2,3}));
// 위 2가지 방법의 단점을 해결하는 가장 좋은 방법이 가변 인수를 만들어 사용하는 방법이다.
System.out.println("total(1,2,3,4,5) : " + mt.total(1,2,3,4,5));
System.out.println("total(1,2,3,4,5) : " + mt.total(1,2,3,4,5,6,7,8));
}
}
----
//오버라이딩
// 예) 2차원 좌표계의 한 점을 표현하기 위한 Point 클래스가 있을 때,
class Point {
// x, y축
int x;
int y;
String getLocation() {
return "x: "+ x + "y: "+ y;
}
}
//이를 조상으로 하는 Point3D클래스, 3차원 좌표계의 한점을 표현하기 위한 클래스를 다음과 같이 새로 작성하였다고 하자.
class Point3D extends Point {
int z;
String getLocation() {
return "x: "+ x + "y: "+ y + "z: "+ z;
}
}
---
// 개념 체크퀴즈
class Parent {
void parentMethod() {}
}
class Child extends Parent {
void parentMethod() {} // 오버라이딩
void parentMethod(int i ){} //오버로딩
void childMethod() {}
void childMethod(int i){} // 오버로딩
void childMethod() {} //에러, 중복 정의 되었음.
}
------------------
// 오버라이딩 실습
public class Car {
String brand;
String color;
int price;
public Car() {;}
public Car(String brand, String color, int price) {
super();
this.brand = brand;
this.color = color;
this.price = price;
}
void engineStart() {
System.out.println(brand + " 열쇠로 시동 켜기");
}
void engineStop() {
System.out.println(brand + "열쇠로 시동 끄기");
}
}
--------
public class SuperCar extends Car {
// 상속 필드 추가
String mode;
public SuperCar() {;}
public SuperCar(String brand, String color, int price, String mode) {
// 생성자는 자동으로 상속이 안됨, super(파라미터적어 주던지) or this.brand=brand ... 로 적어줘야함
super(brand, color, price);
this.mode = mode;
}
void engineStart() {
System.out.println(brand+"음성으로 시동켜기");
}
void engineStop() {
System.out.println(brand+"음성으로 시동끄기");
}
void roofOpen() {
System.out.println(brand+"뚜껑 열기");
}
void roofClose() {
System.out.println(brand+"뚜껑 닫기");
}
}
-----------
public class Road {
public static void main(String[] args) {
Car car = new Car ("K5", "black", 5000 );
SuperCar myCar = new SuperCar ("람보르기니" , "Black", 10000, "데일리");
car.engineStart();
myCar.engineStart();
}
}
---
//다형성
class Person{}
class Student extends Person{}
public class Day09 {
public static void main(String[] args) {
// 정상 에러날 이유 없음
Student s1 = new Student();
// 정상, 하위 클래스로 객체를 만들면서 타입은 부모타입을 쓰는것이 가능(다형성)
Person s2 = new Student();
// 정상
Person aaa = new Person();
// 상위 클래스로 객체를 생성하면서 타입은 하위타입을 쓰는경우는 에러
// Student bbb = new Person();
}
}
-----------------------
// 다형성 2
class Person{
String str1 = "난부모 클래스";
void method1() {System.out.println("에이에이에이");}
// 부모클래스의 독자적 메서드
void ppp() {System.out.println("ppp");}
}
class Student extends Person{
String str2 = "난자식 클래스";
// 그 내용을 덮어쓴것, 재정의해서 사용하겠다
void method1() {System.out.println("오버라이딩-AAA");}
void sss() {System.out.println("sss");}
// 마지막
void x(){
method1(); // 위의 메서드1 을 호출하는 것
super.method1(); // 슈퍼는 부모를 가르키는것. 부모의 메서드를 자식 클래스에서 가져올 수 있음
}
}
public class Day09 {
public static void main(String[] args) {
Student s1 = new Student();
System.out.println(s1.str1);
System.out.println(s1.str2);
s1.method1();
s1.sss();
// 자식클래스에 있는 모든 자원 사용이 가능하다.
// 부모클래스에 있는 모든 자원 사용이 가능하다.
s1.ppp();
// 여기서 질문! 자식클래스에서 오버라이딩 된 브모클래스의 원본 메서드를 호출하고 싶다면? > 슈퍼
// d위의 void x 클래스 에서의 method1에 슈퍼를 붙이면 된다.
s1.x();
// 정상, 하위 클래스로 객체를 만들면서 타입은 부모타입을 쓰는것이 가능(다형성) , 부모의 자원만 쓸수 있다(?)
Person s2 = new Student();
System.out.println(s2.str1);
// System.out.println(s2.str2); //err
s2.ppp();
// s2.sss(); // 자식의 자원을 쓸수 없다.
s2.method1(); // 오버라이딩 - AAA --> 오버라이딩한거는 자식의 메서드로 실행.
// 부모클래스에 없는 자식의 메서드를 바로 호출하고 싶다면? --> 캐스트 필요
((Student)s2).sss();
// 정상
Person aaa = new Person();
aaa.method1();// 에이에이에이
//aaa.sss();
// 상위 클래스로 객체를 생성하면서 타입은 하위타입을 쓰는경우는 에러
// Student bbb = new Person();
}
}
728x90
반응형