생활코딩/생활코딩 Java

Java_객체 지향 프로그래밍 - 활용 - 인스턴스화

양상추상츄 2021. 10. 13. 12:49

https://www.youtube.com/watch?v=1KWFFwtM4Kg&t=654s 

 

 

package projectOOP; 

class Accounting {
    // 공급가액
    public double valueOfSupply; // static을 지워야 어느 인스턴스를 말하는지 알 수 있음
    // 부가가치세율
    // 부가세는 10%로 지정되어 있기 때문에 모든계산할때 같은 값으로 해야함 그러므로 static필요
    //나중에 변경하면 모든 계산에 다 적용된다. 메모리 활용에도 도움됨
    public static double vatRate = 0.1; 
    
    public Accounting(double valueOfSupply) {//생성자 생성
        this.valueOfSupply = valueOfSupply; //this는 인스턴스를 가리킴
    }
 
    public double getVAT() {
        return valueOfSupply * vatRate;
    }
     
    public double getTotal() {
        return valueOfSupply + getVAT();
    }
}

public class AccountingApp_1 {

    public static void main(String[] args) {
     Accounting a1 = new Accounting(10000.0);
     //a1.valueOfSupply = 10000.0; //생성자 생성으로 필요없어짐
    
     Accounting a2 = new Accounting(20000.0);
     //a2.valueOfSupply = 20000.0;
    
     System.out.println("Value of supply : " + a1.valueOfSupply);
     System.out.println("Value of supply : " + a2.valueOfSupply);
    
     System.out.println("VAT : " + a1.getVAT());
     System.out.println("VAT : " + a2.getVAT());
    
     System.out.println("Total : " + a1.getTotal());
     System.out.println("Total : " + a2.getTotal());
    
     //기존코드
     //공급가가 계속 바뀌는 상황에서 값을 구해야 될경우 아래 처럼 복잡해짐. 버그가 생길 가능성 커짐
//     Accounting.valueOfSupply = 10000.0;
//        System.out.println("Value of supply : " + Accounting.valueOfSupply);
//        Accounting.valueOfSupply = 20000.0;
//        System.out.println("Value of supply : " + Accounting.valueOfSupply);
//        
//        Accounting.valueOfSupply = 10000.0;
//        System.out.println("VAT : " + Accounting.getVAT());
//        Accounting.valueOfSupply = 20000.0;
//        System.out.println("VAT : " + Accounting.getVAT());
//        
//        Accounting.valueOfSupply = 10000.0;
//        System.out.println("Total : " + Accounting.getTotal());
//        Accounting.valueOfSupply = 20000.0;
//        System.out.println("Total : " + Accounting.getTotal());
        //...

    }
}