메소드간 .으로 연결되어 계속 사용하는 일련의 것을 메소드 체인이라고 한다.
p1.getName().equals(p2.getName())
this는 해당 클래스내의 멤버변수를 가르킬 때 사용하고
this()는 해당 클래스 내의 오버로딩(매개변수가 다른) 생성자를 호출할때 사용한다.
아래 코드는 예제다.
public class Student {
String name;
int age;
String addr;
public Student(String name, int age, String addr) {
super();
System.out.println("매개변수 3개짜리 생성자");
this.name = name;
this.age = age;
this.addr = addr;
}
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(String name) {
this(name, 20, "미상");
System.out.println("매개변수 1개짜리 생성자");
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", addr=" + addr + "]";
}
}
생성자의 첫 라인에는 객체생성관련된 것이 첫 라인에 와야함. 그렇지 않으면 에러남.
public Student(String name) {
this(name, 20, "미상");
System.out.println("매개변수 1개짜리 생성자");
}
만약에 위 코드에서 첫 라인에 출력문을 넣으면 오류가 발생한다.
데이터타입, 인자의 갯수, 순서에 영향을 받음
다른 패키지를 사용하기 위해서는 import가 필요하다.
import java.util.Random;
import com.xxx.Student;
public class TestStudent {
public static void main(String[] args) {
Student s = new Student();
Random r = new Random();
}
}
또는 직접 패키지명을 객체를 사용할때마다 적어줘도 된다.
public class TestStudent2 {
public static void main(String[] args) {
com.xxx.Student s = new com.xxx.Student();
com.yyy.Student s2 = new com.yyy.Student();
}
}
자동 import : 컨트롤 + 쉬프트 + O
그림으로 그리기
여러개의 객체 생성시 데이터를 다루기 어렵다. 배열을 이용해서 해결해보자.
사용 : x[0].멤버변수 / x[0].메소드 등으로 사용가능하다.
Student stu = new Student("홍길동1", 1, "서울1");
Student stu2 = new Student("홍길동2",2,"서울3");
Student stu3 = new Student("홍길동3",3,"서울4");
Student [] yy = {stu, stu2, stu3};
Student [] sa2 = new Student[3];
sa2[1] = stu01;
sa2[2] = stu02;
sa2[3] = stu03;
배열에서의 max값을 구할 때.
max에 값을 직접 저장해서 비교하는 것이 아니라, index를 비교하는 아이디어가 있음.
메모리적으로 이게 더 효율적으로 보임. 대신 계산에 들어가는 시간은 조금 더 걸릴 수 있음.
객체생성x
객체와 상관없이 변수가 따로 만들어져서 모든 객체들의 공유변수가 된다.
클래스이름.변수명 으로 사용가능
인스턴스는 new를 이용한 객체생성을 할 때 마다 생성되지만 클래스는 단 한번만 생성된다.
객체생성과 전혀 관련이 없다.
static 함수 내에서 일반 멤버 변수 사용 불가능
(교제 한번 읽어봐야함 이거)
한파일에 2개의 클래스가 있을때
파일 이름과 같은 클래스는 퍼블릭이 붙어야함