자바 시작하기 - 문법5

지니·2023년 5월 16일
0

자바 기초

목록 보기
5/7
post-thumbnail

객체지향

객체 = 물건, 사물
물건과 사물은 속성, 기능을 가지고 있다.

속성은 정적인 정보이다. 멤버 변수
기능은 동적으로 수행할 수 있는 역할 혹은 움직임을 가리킨다. 메서드

객체 지향에서 중요한 것은 사물의 공통점을 묶는 과정이다.
그 관계를 구조화하여 코드로 구현하는 것이 자바 객체지향의 핵심이다.

설계 역할 - 클래스
생산이 된 결과물 - 인스턴스

클래스

은행의 계좌에서 일어나는 작업들을 속성과 기능을 나눠 구현해보자.

public class BankAccount {
   //멤버변수
   int bankCode;
   int accountNo;
   String owner;
   int balance;
   boolean isDormant;
   int password;
   
   //메서드
   void inquiry() {}
   void deposit() {}
   void withdraw() {}
   void heldInDormant() {}
   
   //생성자: 클래스 내부에 정의, 생성자 메서드명은 클래스명과 일치해야 한다.
   //new 연산자와 함께 사용해야 한다.
   BankAccount(
         int bankCode,
         int accountNo,
         String owner,
         int balance,
         boolean isDormant,
         int password
   ) {
      this.bankCode = bankCode; //왼쪽의 bankCode는 클래스에 정의된 멤버변수를 의미하고, 오른쪽의 bankCode는 사용자로부터 입력받은 값을 의미한다.
      this.accountNo = accountNo;
      this.owner = owner;
      this.balance = balance;
      this.isDormant = isDormant;
      this.password = password;
   }
}   

// 새로운 클래스를 생성한다.

public class classEx {
   public static void main(String[] args) {
      
      BankAccount account = new BankAccount();
      System.out.println(account);
      System.out.println(account.bankCode);
      System.out.println(account.isDormant);
   }
}

상속

//새로운 클래스 생성
// extends를 이용하여 BankAccount 내용을 전부 가져와 재활용 가능

public class SaveAccount extends BankAccount {
   
   boolean isOverdraft;
   void transfer() {};
   
}

//달러를 이용하는 새로운 클래스 생성

public class DallorAccount extends BankAccount {
   
   void inquiry() {}
}

//청약통장을 이용하는 새로운 클래스 생성

public class SubscriptionAccount extends BankAccount {
   
   int numOfSubscription;
}

BankAccount에 있는 모든 것들을 하나하나 Account에 쓰는 것이 아니라 extends키워드로 부모 클래스에 멤버변수와 메소드를 모두 상속받아 활용하면 효율적으로 객체 간의 관계를 구성할 수 있다.

상속할 때 주의점으로는, extends 뒤에 하나의 클래스만 상속할 수 있다.

오버로딩

오버로딩: 부모 클래스에서 상속받은 메소드에서 파라미터를 변경하여, 새로운 메소드를 정의하는 것이다.

public class DallorAccount extends BankAccount {
   
   void inquiry(double currencyRate) {}
}

오버라이딩

오버라이딩: 부모 클래스에서 상속받은 메소드의 내용을 자식 클래스의 상황에 맞게 변경하는 것이다.
부모 클래스의 파라미터 설정을 그대로 따른다.

public class DallorAccount extends BankAccount {
   
   void inquiry(double currencyRate) {}
   
   void deposit() {
       
   }
}

접근제어자

접근제어자는 클래스 혹은 클래스 안의 멤버변수, 생성자에 대한 것들의 접근을 제한한다.
일반적으로 타입 앞에 나타내게 된다.

접근제어자를 정의해주지 않으면 아무나 데이터에 접근가능해진다. (보안, 안전성에 위험)

public class classEx {
   public static void main(String[] args) {
      
      BankAccount bankAccount = new BankAccount();
      bankAccount.password = 1234;
      System.out.println(bankAccount.password);
   }
}

비밀번호를 임의로 바꿀 수 있다.
패스위드를 바꾸는 일정한 규칙이 있을 시, 임의로 데이터를 덮었을 때 규칙에 맞지 않는 데이터가 들어갈 수 있다.

인스턴스의 속성은 임의로 데이터를 덮어 데이터를 변경하는 것이 아니라, 각각의 역할에 맞는 함수를 만들어 변경한다.

public class BankAccount {
   //멤버변수
   private int bankCode;
   private int accountNo;
   private String owner;
   private int balance;
   private boolean isDormant;
   private  int password;
   
   //메서드
   void inquiry() {}
   void deposit() {}
   void withdraw() {}
   void heldInDormant() {}
   
   //생성자: 클래스 내부에 정의, 생성자 메서드명은 클래스명과 일치해야 한다.
   //new 연산자와 함께 사용해야 한다.
   BankAccount(
         int bankCode,
         int accountNo,
         String owner,
         int balance,
         boolean isDormant,
         int password
   ) {
      this.bankCode = bankCode; //왼쪽의 bankCode는 클래스에 정의된 멤버변수를 의미하고, 오른쪽의 bankCode는 사용자로부터 입력받은 값을 의미한다.
      this.accountNo = accountNo;
      this.owner = owner;
      this.balance = balance;
      this.isDormant = isDormant;
      this.password = password;
   }
}   

private으로 접근을 막는다. 동일 클래스에서만 참조 및 수정이 가능하다.

public class BankAccount {
   //멤버변수
   private int bankCode;
   private int accountNo;
   private String owner;
   private int balance;
   private boolean isDormant;
   private  int password;
   
   //메서드
   public void inquiry() {}
   public void deposit() {}
   public void withdraw() {}
   public void heldInDormant() {}
   
   public void changepassword(int password) {
      this.password = password
   }
   //생성자: 클래스 내부에 정의, 생성자 메서드명은 클래스명과 일치해야 한다.
   //new 연산자와 함께 사용해야 한다.
   BankAccount(
         int bankCode,
         int accountNo,
         String owner,
         int balance,
         boolean isDormant,
         int password
   ) {
      this.bankCode = bankCode; //왼쪽의 bankCode는 클래스에 정의된 멤버변수를 의미하고, 오른쪽의 bankCode는 사용자로부터 입력받은 값을 의미한다.
      this.accountNo = accountNo;
      this.owner = owner;
      this.balance = balance;
      this.isDormant = isDormant;
      this.password = password;
   }
}   
public class classEx {
   public static void main(String[] args) {
      
      bankAccount.changepassword = 1234;
   }
}

접근제어한 상태에서 데이터 조회해보기

우클릭 > Generate > Getter

접근제어한 상태에서 데이터 변경해보기

우클릭 > Generate > Setter

접근제어한 상태에서 데이터 조회, 변경해보기

우클릭 > Generate > Getter & Setter

public class classEx {
   public static void main(String[] args) {
      
      bankAccount.changepassword = 1234;
      System.out.println(bankAccount.getPassword());
   }
}

인터페이스

클래스: 상세한 설계도
인터페이스: 스케치

메소드 이름, 파라미터, 반환, 타입만 가질 수 있다.
실제 코드를 구현할 수 없다.

인터페이스는 기능의 표준화를 달성하기 위한 도구이다.
인터페이스는 공통적인 기능을 일정한 단위, 범주로 묶어 처리하여, 구현할 클래스에서 각 업무로직에 맞게 구현을 할 수 있도록 한다.
클래스에 걸쳐서 신규기능이 생기거나 삭제되는 기능이 있다면, 인터페이스의 표준화를 활용해 효율적인 업무가 가능하다.

public class BankAccount {
   //멤버변수
   private int bankCode;
   private int accountNo;
   private String owner;
   private int balance;
   private boolean isDormant;
   private  int password;
   
   //메서드
   public void inquiry() {}
   public void deposit() {}
  
   public void heldInDormant() {}
   
   public void changepassword(int password) {
      this.password = password
   }
   //생성자: 클래스 내부에 정의, 생성자 메서드명은 클래스명과 일치해야 한다.
   //new 연산자와 함께 사용해야 한다.
   BankAccount(
         int bankCode,
         int accountNo,
         String owner,
         int balance,
         boolean isDormant,
         int password
   ) {
      this.bankCode = bankCode; //왼쪽의 bankCode는 클래스에 정의된 멤버변수를 의미하고, 오른쪽의 bankCode는 사용자로부터 입력받은 값을 의미한다.
      this.accountNo = accountNo;
      this.owner = owner;
      this.balance = balance;
      this.isDormant = isDormant;
      this.password = password;
   }
}   

//새로운 자바 클래스의 인터페이스 생성

public interface Withdrawable {

   void withdraw();
}

wirhdraw에 대한 표준화를 시킨 것이다.

세부 클래스에서 구현할 수 있도록 설정해야한다.
클래스 명 옆에 implements를 사용한다.

public class SaveAccount extends BankAccount implements Withdrawable{
   
   boolean isOverdraft;
   void transfer() {};
   
   public void withdraw() {
      System.out.println("Withdraw");
   };
}

예외 처리

try catch문을 이용하여 예외처리를 한다.

ArratList arrayList = new ArrayList(3);
arrayList.get(10);

try{
   arrayList.get(10);
} catch (Exception e) {
   e.printStackTrace(); //에러 내용 출력
   System.out.println("에러발생");
} finally {
   System.out.println("finally");
}

예상되는 에러가 특정이 되면, 특정하여 catch구문에 넣은뒤 세분화한다.

마지막 catch문에는 예상되지 못한 에러를 잡는 Exception을 넣어주는 것이 좋다.

ArratList arrayList = new ArrayList(3);
arrayList.get(10);

try{
  int a = 10;
  int b = 0;
  int c = a / b;
} catch (IndexOutOfBoundsException ioe) {
  System.out.println("IndexOutOfBoundsException 발생");
} catch IllegalArgumentException iae() {
  System.out.println("IllegalArgumentException 발생");
} catch (Exception e) {
  System.out.println("Exception 발생");
} finally {
  System.out.println("finally");
}
profile
IT학과 전과생

0개의 댓글