Java_Week_5

신태원·2020년 10월 4일
0

Java

목록 보기
5/7
post-thumbnail

Classes and Objects

  • this
    -> c++에서도 있지만, 객체 자신을 가리키는 것.
class SimpleTime {
   private int hour, minute, second;
   
   public SimpleTime( int hour, int minute, int second) { // bad naming but ..
      this.hour = hour;
      this.minute = minute;
      this.second = second;
}
...
}
//instance 변수 hour와 parameter hour

-> this는 또한 메소드로 사용 가능. 오버로딩과 함께 사용한다. 다음 코드를 보자.

public class Time2Test
{
   public static void main( String[] args)
   {
      Time2 t1 = new Time();
      Time2 t2 = new Time(2);
      Time2 t3 = new Time(21, 34);
      Time2 t4 = new Time(12, 25, 42);
      Time2 t5 = new Time(27, 74, 99);
      Time2 t6 = new Time(t4);
      
      System.out.printLn("Constructed with:");
      System.out.printLn("t1: all arguments defaulted");
      System.out.printLn("%s\n", t1.toUniversalString());
      System.out.printLn("%s\n", t1.toString());
      
      System.out.printLn(
         "t2: hour specified; minute and second defaulted" );
      System.out.printLn("%\n", t2.toUniversalString());
      System.out.printLn("%s\n", t2.toString());
   }
}

public class Time2
{
   private int hour;
   private int minute;
   private int second;
   
   //밑에 있는 것들은 다 생성자들임. 다만 overloading이기 때문에, parameter들은 다 다름.
   public Time2()
   {
      this(0, 0, 0);
   }
   
    public Time2(int h)
   {
      this(h, 0, 0);
   }
   
    public Time2(int h, int m)
   {
      this(h, m, 0);
   }
   
    public Time2(int h, int m, int s)
   {
      this(h, m, s);
   }
   
    public Time2(Time2 time)
   {
      this(time.getHour(), time.getMinute(), time.getSecond());
      //요거는 저런 메소드가 있다고 가정하고 써놓은거임.
   }
   
}

Defult Constructor

  • 원래는 생성자가 있어야 하지만, 없어도 자동으로 뭘 해주는데, 숫자 type인 경우 0, boolean 값인 경우는 false, 객체인 경우에느 null 로 초기화 됨.

Garbage collection

  • c++과는 다르게 자바는 자동으로 쓰지 않는 쓰레기 메모리 값들을 collection해준다.
  • object들을 직접 delete 할 수 없음.
  • a라는 포인터가 객체를 가리키고 있었는데, 더 이상 필요없으니 null값을 넣어주는 형태로 '도와줄 수는 있음'
  • 그래서 훨씬 safe한 언어이다.

static member

  • static field
    -> class variable이라 부르고, class의 모든 instance들이 공유할 수 있다.
  • static method
    -> class method라고 부르고,

static은 프로그램이 실행될 때 메모리 영역에 할당되므로, 인스턴스 과정(객체생성)없이 모두가 접근할 수 있는 공유자원인 것이다.
여기서 추가로 볼 것은, 모두가 접근할 수 있는 공유자원이기 때문에 static에는 this라는 내것이라는 개념이 존재하지 않는다.
[출처] https://gangnam-americano.tistory.com/20

static import

  • 예를들어서 import static java.lang.Math.*; 라고 해주면, 모든 메소드에 Math를 붙힐 필요가 없음.

final variables

  • 값 변경 불가.
  • 선언하면서 초기화하거나, 생성자에서 딱 한번만 바꿀 수 있음.
profile
일단 배우는거만 정리해보자 차근차근,,

0개의 댓글