6-1.
Class Student {
String name;
int ban;
int no;
int kor;
int eng;
int math;
}
6-2. 생성자와 info() 추가하기
완전 헤맸다... ㅜㅜ
Class Ex6_2 {
public static void main(String args[]) {
Student s = new Student ("홍길동", 1, 1, 100, 60, 76); // 객체 s 생성.선언& 인스턴스를 저장
String str = s.info(); // 참조변수.멤버변수
System.out.println(str);
}
}
Class Student { // Student의 멤버변수(인스턴스 변수)
String name;
int ban;
int no;
int kor;
int eng;
int math;
Student (string name, int ban, int no, int kor, int eng, int math) { //매개변수가 있는 생성자 호출.
this.name = name;
this. ban = ban;
this.no = no;
this.kor = kor;
this.eng = eng;
this.math = math;
}
public String info() { // 메서드
return +name+
"," +ban +
","+no+
","+kor+
","+eng+
","+math+
","+(kor+eng+math)+
","+((int)((kor+eng+math)/3f * 10 + 0.5f) /10f);
}
6-3. 2번이랑 비슷
class Ex6_Exercise {
public static void main(String args[]) {
Student s = new Student();
s.name = "홍길동";
s.ban = 1;
s.no = 1;
s.kor = 100;
s.eng = 60;
s.math = 76;
System.out.println("이름: " + s.name);
System.out.println("총점: "+ s.getTotal());
System.out.println("평균: "+s.getAverage());
}
}
class Student {
String name ;
int ban;
int no;
int kor;
int eng;
int math;
int getTotal() {
return kor + eng + math;
}
float getAverage() {
return (int)((kor + eng + math) * 10 / 3f + 0.5) /10f;
}
}
6-4. 제곱근 계산 => Math.sqrt(double a)
두 점의 거리 계산 -> a제곱 + b제곱 의 루트
class Ex6_Exercise {
static double getDistance(int x, int y, int x1, int y1) {
return Math.sqrt((y1 - y)*(y1-y)+(x1 - x)*(x1-x)); // x, y는 지역변수
}
public static void main (String[] args) {
System.out.println(getDistance(1,1,2,2));
}
}
6-5. 변수종류 구분
6-6. getDistance의 변수설정 good.
6-4에서는 static메서드 사용함. - 메서드 내에서 인스턴스 변수 사용하지 않음.!!! 지역변수로 작업에 필요한 값을 제공받음.
6-6에서는 인스턴스 변수 x, y사용했으므로 static 붙일 수 없다.
class MyPoint {
int x;
int y;
MyPoint(int x, int y) {
this.x = x;
this.y = y;
}
Double getDistance(int x1, int y1) {
return Math.sqrt((x1 - x)*(x1-x) +(y1-y)*(y1-y));
}
}
class Ex6_Exercise {
public static void main(String[] args) {
MyPoint p = new MyPoint(1,1);
System.out.println(p.getDistance(2,2));
}
}
6-7. static 붙이는 멤버 : static + weapon, armor, weaponUp(), armorUp()
6-8.
1. 모든 생성자의 이름은 클래스의 이름과 동일해야 한다.
2. 생성자는 객체를 생성할 때 사용되기는 하지만, 객체를 초기화할 목적으로 사용되는 것. 객체 생성하는 것은 new연산자.
3. 클래스에는 생성자가 반드시 하나 이상 있어야 한다.
4. 생성자가 없는 클래스는 컴파일러가 기본 생성자를 추가한다.
5. 생성자도 오버로딩이 가능해서 하나의 클래스에 여러 개의 생성자를 정의할 수 있다.
6-9. this
1. 객체 자신을 가리키는 참조변수이다.
2. 클래스 내에서라면 어디서든 사용할 수 있지 않아. (인스턴스 메서드에서만 사용가능) 클래스 멤버에는 사용할 수 없다.
3. 지역변수와 인스턴스변수를 구별할 때 사용한다.
4. 클래스 메서드 내에서는 사용할 수 없다.