✨
Java
  • 자바의 역사
  • Ch1
    • Before Start Java
      • History of Java
      • Feature of Java
      • API Documentation
      • Hello World!
      • eclipse shortcut
      • Eclipse IDE
      • GitHub to eclipse
  • Ch2
    • Variable
      • Variable
    • Variable Type
    • Character and String
    • Primitive type and range
    • printf and formatter
    • Scanner
    • Overflow of Int
    • Transition between different variable types
    • Object Array
  • CH3
    • Operator
  • CH4
    • 조건문과 반복문
    • if statement
    • switch
    • Math.random()
    • for statement
    • while statement
    • break, continue, named iterated statement
  • CH5
    • Array
    • 배열 활용
    • String Array
  • OOP
    • Intro
  • Class and Object
  • Make multiple Classes in one file
  • How to use Object
  • Object Array
  • Variable type according to declared location
  • Class Variable and Instance Variable
  • Method
  • Call Stack
  • Parameter
  • Static method(Class method) and Instance method
  • (Method)Overloading
  • Constructor
  • Constructor this()
  • Reference type variable "this"
  • Initialize variable
  • Inheritance
  • Composite
  • Single Inheritance, Object Class
  • (Method)Overriding
  • super, super()
  • package, class path
  • import, static import
  • modifier
  • access modifier
  • Encapsulation
  • Polymorphism
  • reference type transition
  • instanceof operator
  • Parameter polymorphism
  • Multiple object using one array
  • Abstract Class, Abstract Method
  • Creating Abstract Class
  • Interface
  • Interface Polymorphism
  • Interface Pros
  • Default method and static method
  • Inner Class
  • Anonymous Class
  • java.lang package and useful class
    • Object class
    • hashCode(), toString()
    • String class
    • StringBuffer class
    • StringBuilder class
    • Math class
    • Wrapper class
    • Number class
    • String to Number, String to Wrapper class
    • Auto-boxing and (auto)Unboxing
  • Collection Framework
    • Collections framework
    • List, Set, Map Interface
    • List의 removeAll() 과 clear() 비교
    • List Interface - ArrayList
    • How to view Java API source
    • List Interface - LinkedList
    • Stack and Queue
    • Iterator, ListIterator, Enumeration
    • Array
    • Comparator와 Comparable
    • Stack
    • String
    • String + char = String
    • String.toCharArray()
    • BufferedReader / BufferWriter
    • Scanner로 String 입력 - next( )와 nextLine( )
    • 공백없이 2차원배열 데이터 String으로 한번에 한줄씩 입력받기(문자/숫자)
    • 공백을 사이에 두고 빠른 2차원 배열 입출력
    • arr[index++]과 arr[index] index++의 차이
    • int와 long의 차이
    • Untitled
    • 타입 간의 변환
    • Array 와 ArrayList
    • valueOf()
    • Char
    • 변수, 객체 초기화(초기값 설정)
  • error troubleshooting
    • No enclosing instance of type
    • ASCII Code Table
    • java.lang.NumberFormatException
    • No enclosing instance..
  • reference
    • String을 생성하는 2가지 방법과 차이점
    • StackOverflowError(스택, 힙 메모리)
    • swtich-case 반복문
Powered by GitBook
On this page

Was this helpful?

Parameter polymorphism

부모 클래스 매개변수에 자식 클래스도 들어갈 수 있다!

참조형 매개변수는 메소드 호출시, 자신과 같은 타입 또는 자손 타입의 인스턴스를 넘겨줄 수 있다.

Pros and Cons of parameter polymorphism

  • Pros

  1. 다형적 parameter : 참조형 매개변수는 메소드 호출시, 자신과 같은 타입 또는 자손 타입의 인스턴스를 넘겨줄 수 있다.

  2. Multiple object using one array

다형성이란

  1. 조상 객체 참조변수로 자손 객체 다룰 수 있다.

Tv t = new SmartTv();

2. 참조 변수 형변환 - 리모콘 바꾸기(control the number of usable members;사용가능한 멤버 갯수 조절)

3. instanceof operator : check casting(형변환 가능여부 확인할 때 쓰인다.)

*오버로딩 : 메소드 이름 같고, 매개변수 타입 다른 것.

아래의 코드는 많은 오버로딩으로 인해 코드의 유지보수가 어려워지고 코드가 중복되는 단점이 있다.

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) {
        money -= p.price;
        bonusPoint += p.bonusPoint;
    }
}

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;
}

개선된 코드 :

class Product {
    int price;
    int bonusPoint;
    //constructor, initialize an object
    Product(int price) {
        //Product(100)하면 그 Product의 price가 100으로 초기화된다.
        this.price = price;
        this.bonusPoint = (int)(price/10.0);
    }
}
class Tv1 extends Product {
    Tv1() {
        //Product(int price)를 호출한다.(조상클래스의 생성자를 호출)
        super(100);
    }
    
    //Object 클래스의 toString()을 오버라이딩한다.
    public String toString(){return "Tv";};
}
class Computer extends Product {
        Computer() {super(200);}
    
    public String toString() {return "Computer";}
}

class Buyer {
    int money = 1000;
    int bonusPoint = 0;
    
    void buy(Product p) {
        if(money < p.price) {
            System.out.println("잔액이 부족합니다.");
            return;
        }
        
        money -= p.price;
        bonusPoint += p.bonusPoint;
        System.out.println(p + "을/를 구입하셨습니다.");
        //System.out.println(p.toString() + "을/를 구입하셨습니다.");
    }
}

class Ex7_8 {
    public static void main(String args[]) {
        Buyer b = new Buyer();
        
        //Product p = new Tv1();
        //b.buy(p);
        b.buy(new Tv1());
        b.buy(new Computer());
        
        System.out.println("현재 남은 돈은 " + b.money + "만원입니다");
        System.out.println("현재 보너스 점수는 " + b.bonusPoint + "점입니다");
        
    }
}

Previousinstanceof operatorNextMultiple object using one array

Last updated 4 years ago

Was this helpful?