//////
Search
📓

09/24 상속, Overriding, 다형성, 과제1~3

생성일
2022/09/26 07:16
태그

상속(inheritance) - 임학준

상속과 생성자

상속은 재사용의 개념도 있지만 공통적인것을 묶어 소스코드를 간결하게 하기위함도 있다
생성자의 호출순서는 부모클래스 먼저 다음 자식클래스 순이다
자식 클래스 객체안에는 부모클래스에서 상속된 부분이 존재한다
자식클래스 안의 부모 클래스 부분을 초기화하기 위하여 부모클래스 생성자도 호출한다
class A{ public A() { System.out.println("A생성자 호출"); } } class B extends A{ public B() { System.out.println("B생성자 호출"); } } public class SuperTest { public static void main(String[] args) { B b = new B(); //B클래스를 실행했지만 부모클래스 A클래스 먼저 실행 //부모생성자가 호출되면서 제일위에 위치 //이말은 메모리에 부모가 먼저 올라간다 } } /*출력결과 A생성자 호출 B생성자 호출*/
Java
복사

super(); 부모생성자

this();생성자가 자기자신을 가리키는것과 달리 super();는 부모생성자를 가리킨다
개발자가 super을 넣지않으면 컴파일러가 기본적으로 넣어준다
이미 생성된 생성자가 있으면 기본생성자가 생성되지않는다
현업에서는 기본적으로 기본생성자를 넣어주는 습관을 길러야 한다.
class A{ public A() { //기본생성자 System.out.println("A생성자 호출"); } } class B extends A{ public B() { super();//부모생성자 this();는 자기자신 //파라미터가 없다 public A();호출 //개발자가 생성하지않으면 컴파일러가 기본으로 넣는다 System.out.println("B생성자 호출"); } } public class SuperTest { public static void main(String[] args) { //A a = new A(); B b = new B(); } }
Java
복사

protected 접근 제한자

같은 패키지에서는 접근제한이 없지만 다른 패키지에서는 자식 클래스만 접근을 허용한다
protected는 필드와 생성자,메소드 선언에 사용 할 수 있다
package protect; public class A{ protected String field; protected A() { } protected void method() { } } ---------------------------------------- package protect2; //패키지가 다르다 import protect.A; public class B extends A{ //A클래스를 상속 public B() { super(); this.field = "value"; // 접근가능 this.method(); } }
Java
복사

오버라이딩(Overriding) - 김상호

오버로딩이란?

같은 이름의 메소드를 중복하여 정의하는 것 원래 자바에서는 한 클래스 내에 같은 이름의 메소드를 둘 이상 가질 수 없는데, 매개변수의 개수나 타입을 다르게 하면, 하나의 이름으로 메소드를 작성가능
ex)
void println(int x) void println(String x) void println(long x) . . .
Plain Text
복사

오버로딩이 성립하기 위한 조건

메소드 이름이 같아야 함
1.
매개변수의 개수 또는 타입이 달라야 함
2.
변환타입엔 영향끼치지 않는다.
double add(int a, double b) {return a+b;} double add(double a, int b) {return a+b;}
Plain Text
복사

오버로딩 예제 코드

class Test { static void display(int num1) { System.out.println(num1); } static void display(int num1, int num2) { System.out.println(num1 * num2); } static void display(int num1, double num2) { System.out.println(num1 + num2); } } public class Method06 { public static void main(String[] args) { Test myfunc = new Test(); myfunc.display(10); myfunc.display(10, 20); myfunc.display(10, 3.14); myfunc.display(10, 'a'); } }
Plain Text
복사
출력결과
10 200 13.14 970
Plain Text
복사

오버라이딩이란?

위에 덮어쓰다 라는 뜻으로 상속받은 메소드의 내용을 재정의하는 것 (change)
class Exployee { public int getSalary() { return 0; } } class Manager extends Exployee { @Override public int getSalary() { return 5000000; } } class Programmer extends Exployee { @Override public int getSalary() { return 6000000; } } public class salary { public static void main(String[] args) { Manager obj1 = new Manager(); System.out.println("관리자의 월급: " + obj1.getSalary()); Programmer obj2 = new Programmer(); System.out.println("관리자의 월급: " + obj2.getSalary()); } }
Plain Text
복사
출력 결과
관리자의 월급: 5000000 관리자의 월급: 6000000
Plain Text
복사
getSalary 를 오버라이딩 한 것이다.

주의할 점

메소드 앞에 final을 붙이면 해당 메소드는 더 이상 오버라이딩을 할 수 없다. 클래스 앞에 final이 붙어도 해당 클래스를 상속 할 수 없다.

정리

표로 간단하게 정리하자면 이렇게 정리할 수 있다.

다형성(polymorphism) - 이가현

다형성

상속관계일때 적용가능함.
조상클래스 타입의 찹조변수로 자손클래스의 인스턴스를 참조하는 것
자손타입의 참조변수로 조상타입의 인스턴스를 참조하는것은 불가능
왜 불가능할까? 자손타입의 참조변수로 조상타입의 인스턴스를 참조하는 것은 존재하지않는 멤버를 사용할 수 있기 때문에 허용되지 않는다

참조변수의 형변환

서로 상속관계에 있는 클래스사이에서만 가능
형제관계끼리는 형변환 안됨
자손타입→조상타입(up-casting) : 형변환 생략가능 자손타입←조상타입(down-casting):형변환 생략불가 * 생략부분 헷갈리니깐 형변환할때 무조건 붙이기

instanceof 연산자

조건문에 주로 사용
참조변수 instanceof 타입(클래스명) →결과 true,false
true라는 것은 검사한 탑입으로 형변환이 가능하다는 것을 의미한다
if( c instanceof FireEngine){ FireEngine fe = (FireEngine)c; fe.water(); }
Java
복사

매개변수의 다형성

참조형 매개변수는 메서드 호출시 자신과 같은 타입 또는 자손 타입의 인스턴스를 넘겨줄 수 있다.
재사용성, 반복을 줄여줄 수 있다.
// 다형성을 고려하지 않은 코딩 class Product { int price; int bonusPoint; } class Tv extends Product{} class Computer extends Product{} class Audio extends Product{} class Buyer { int money =1000; int bonusPoint =0; void buy(Tv t) { money-=t.price; bonusPoint +=t.bonusPoint; } void buy(Computer c) { money-=c.price; bonusPoint +=c.bonusPoint; } void buy(Audio a) { money-=a.price; bonusPoint +=a.bonusPoint; } }
Java
복사
//다형성을 고려한 코드 class Product { int price; int bonusPoint; } class Tv extends Product{} class Computer extends Product{} class Audio extends Product{} class Buyer { int money =1000; int bonusPoint =0; void buy(Product p) { //조상타입 product를 매개변수로 사용 money-=p.price; bonusPoint +=p.bonusPoint;
Java
복사

여러 종류의 객체를 배열로 다루기

조상타입의 참조변수 배열을 사용하면 공통의 조상을 가진 서로 다른 종류의 객체를 배열로 묶고 공통조상 클래스의 타입의 참조변수 배열을 생성하여 객체를 저장하면 된다.
조상 클래스 product , 자손 클래스 Tv, Computer, Audio일때
product p1 = new Tv();
product p2 = new Computer();
product p4 = new Audio();
Product 타입의 참조변수 배열로 변환
Product p[] = new Product[3];
p[0] = new Tv();
p[1] = new Computer();
p[2] = new Audio();

과제1(Employee) - 최아영

class Employee { String name; int age; String address; String department; int salary; public Employee(String name, int age, String address, String department) { this.name = name; this.age = age; this.address = address; this.department = department; } public void printInfo() { System.out.println("이름: " + name + "\n나이: " + age + "\n주소: " + address + "\n부서: " + department); } } class Regular extends Employee { public Regular(String name, int age, String address, String department) { super(name, age, address, department); } public void setSalary(int salary) { this.salary = salary; } public void printInfo() { super.printInfo(); System.out.println("정규직\n월급: " + salary); } } class Temporary extends Employee { int hour; int pay = 10000; public Temporary(String name, int age, String address, String department) { super(name, age, address, department); } public void setHour(int hour) { this.hour = hour; this.salary = hour * pay; } public void printInfo() { super.printInfo(); System.out.println("비정규직\n일한 시간: " + hour + "\n급여: " + salary); } } public class EmployeeTest { public static void main(String[] args) { Regular r = new Regular("이순신", 35, "서울", "인사부"); Temporary t = new Temporary("장보고", 25, "인천", "경리부"); r.setSalary(5000000); r.printInfo(); t.setHour(120); t.printInfo(); } }
Java
복사

과제2(Bubble sort) - 조국현

public class BubbleSort { public static void main(String[] args){ int[] arr = {7,4,5,1,3}; int[] result_arr = new int[5]; result_arr=bubbleSort(5,arr); for(int i=0; i<result_arr.length;i++){ System.out.println(result_arr[i]); } } public static int[] bubbleSort(int n, int[] arr){ int temp; for(int i = n; i > 0 ; i--){ for(int j=0;j < i-1;j++){ if(arr[j]>arr[j+1]) { temp=arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } return arr; } }
JavaScript
복사

과제3 - 김기헌

public class Main { public static void main(String[] args) { double sum = 0; Shape[] shape = new Shape[2]; shape[0] = new Rectangle(10.0, 20.0); shape[1] = new Triangle(10.0, 20.0); for (Shape s : shape) { sum += s.getArea(); } System.out.println("넓이의 합:" + sum); } }
Java
복사
public class Shape { private double height, width; public Shape() { } public Shape(double width, double height) { this.height = height; this.width = width; } public double getArea() { return height * width; } }
Java
복사
public class Rectangle extends Shape { private double width = 0, height = 0; public Rectangle() { } public Rectangle(double width, double height) { super(width, height); } @Override public double getArea() { return super.getArea(); } }
Java
복사
public class Triangle extends Shape { private double width = 0, height = 0; public Triangle() { } public Triangle(double width, double height) { super(width, height); } @Override public double getArea() { return super.getArea() / 2; } }
Java
복사