Classes and Objects

man soup·2020년 6월 4일
0

자바 문법

목록 보기
2/15

Declaring Member Variables

  • fields : 클래스 안의 멤버 변수
    • field 선언은 3가지로 구성
      • 0개 이상의 modifier (public, private 등)
      • 필드 타입( int, char 등)
      • 필드 이름
  • local variables : 함수나 코드 블록안의 변수
  • parameters : 함수 선번부 안의 변수

Access Modifiers(접근 제어자)

  • public : 모든 클래스들이 필드에 접근 가능
  • private : 자신만 접근 가능

Providing Constructors for Your Classes

  • 클래스에 생성자를 제공하지 않아도 되지만 조심해야한다.

  • 컴파일러가 자동적으로 아규먼트가 없는 default 생성자를 제공한다.

  • 이 default 생성자는 superclass의 아규먼트가 없는 생성자를 호출한다.

  • 이 경우 만약 superclass에게 아규먼트가 없는 생성자가 없다면 컴파일러는 에러?를 낸다.

  • 만약 명시적인 superclass가 없다면 암시적으로 Object 클래스를 superclass로 가진다.

  • Object class는 아규먼트 없는 생성자를 가지고 있다.

  • superclass의 생성자를 사용할 수 있다.(super를 통해)

  • superclass에게 생성자 아무 것도 없으면 컴파일러가 default 생성자를 통해 Object의 no-arg 생성자 사용하므로 subclass를 no-arg 생성자로 만들 수 있지만, superclass에게 arg있는 생성자 존재할 시 compiler가 default 생성자를 제공안하므로 subclass를 no-arg생성자로 만들 수 없다.

Arbitrary Number of Arguments

  • varargs : 함수에 얼마나 많은 값을 넣을 지 모를 때 사용하는 방법

  • 점3개를 사용 -> 배열처럼 사용가능

  • 예시 :

    • public PrintStream printf(String format, Object... args)
    • printf( "%d %s",num,str) 이거나 printf("%d %s %d %s",num,str,num2,str2) 같이 사용함

Returning a Class or Interface

  • When a method uses a class name as its return type, such as whosFastest does, the class of the type of the returned object must be either a subclass of, or the exact class of, the return type.

  • This technique, called covariant return type, means that the return type is allowed to vary in the same direction as the subclass.

  • 인터페이스를 return type으로 사용할 수 있다. 이 경우 return 되는 객체(object)는 사용된 인터페이스가 구현된 객체여야한다.

Using the this Keyword

  • 인스턴스의 함수와 생성자 안에서 this는 현재 객체의 레퍼런스이다.

  • 인스턴스의 함수와 생성자 안에서 this는 현재 객체의 모든 맴버를 참조할 수 있다.

Using this with a Constructor

  • 생성자 안에서 this 키워드를 같은 클래스의 다른 생성자 호출에 사용할수 있다.

  • 명시적 생성자 호출(깨우기)라고 한다.

Controlling Access to Members of a Class

  • Access level modifier는 다른 클래스가 특정 필드를 사용하거나 함수를 깨울 수 있는지 정한다.

  • 2가지 level이 존재

  • top level : public 또는 package-private(명시적 제어자 없는 경우 뜻함)

  • member level : public, private, protected, package-private(명시적 제어자(modifier) 없는 경우)

  • 클래스가 public 제어자로 선언된 경우 모든 곳에 존재하는 클래스가 public 클래스는 볼 수 있다.

  • 만약 클래스에 제어자가 없다면(default, 또는 package-private이라고도 알려짐) 같은 package에서만 보인다.

  • member level에서도 public과 no modifier는 같은 의미

  • member level에는 private, protected 2종류의 제어자가 추가로 존재

  • private은 자신class만 접근 가능

  • protected는 같은 패키지 + 다른패키지에서 자신을 상속받은 클래스

Static Initialization Blocks

  • static 키워드 + { 초기화 코드 }

  • class body 아무곳에서나 여러번 사용 가능

  • 런타임 시스템이 static 초기화 블록들을 순서대로 호출함

Initializing Instance Members

  • 보통 생성자에서 인스턴스 변수 초기화를 하지만 다른 2가지 방법 사용 가능 : 초기화 블록 또는 final 함수

  • 초기화 블록 : static 블록과 동일(static 키워드만 제거)

  • 자바 컴파일러는 모든 생성자에 초기화 블록을 넣는다. 그래서 중복되는 초기화 코드 여기에 넣으면 여러 생성자에서 자동으로 넣어주니까 좋다.

  • final method : 자식클래스에서 override 할 수 없다.

출처 :
https://docs.oracle.com/javase/tutorial/java/javaOO/index.html

profile
안녕하세요

0개의 댓글