6-1)
public class student {
String name;
int ban;
int no;
int kor;
int eng;
int math;
}
6-2)
public class Exercise6_2 {
public static void main(String[] args) {
Student s = new Student("홍길동", 1, 1, 100, 60, 76);
String str = s.info();
System.out.println(str);
}
}
class Student{
String name;
int ban;
int no;
int kor;
int eng;
int math;
public Student(String name, int ban, int no, int kor, int eng, int math) {
super();
this.name = name;
this.ban = ban;
this.no = no;
this.kor = kor;
this.eng = eng;
this.math = math;
}
public String info() {
String res = name+","+ban+","+no+","+kor+","+eng+","+math+",";
// 총합, 평균
int total = kor+eng+math;
double avg = (double)total/3;
res+=total+","+Math.ceil(avg*10)/10;
return res;
}
}
6_3)
public class Exercise6_3 {
public static void main(String[] args) {
Student s = new Student("홍길동", 1, 1, 100, 60, 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;
public Student(String name, int ban, int no, int kor, int eng, int math) {
super();
this.name = name;
this.ban = ban;
this.no = no;
this.kor = kor;
this.eng = eng;
this.math = math;
}
public float getAverage() {
float avg = (int)((getTotal()/3f*10)+0.5f)/10f;
return avg;
}
public int getTotal() {
return kor+eng+math;
}
}
6_4)
public class Exercise6_4 {
// 두점(x,y)와 (x1,y1)간의 거리를 구한다.
static double getDistance(int x, int y, int x1, int y1) {
double res = 0.0;
res = Math.sqrt((x1-x)*(x1-x)+(y1-y)*(y1-y));
return res;
}
public static void main(String[] args) {
System.out.println(getDistance(1, 1, 2, 2));
}
}
6_5)
- 클래스변수(static변수) :
static int width
static int height
- 인스턴스변수 :
int kind
int num
- 지역변수 :
int k
int n
PlayingCard card
String[] args
6_6)
class MyPoint {
int x;
int y;
public MyPoint(int x, int y) {
super();
this.x = x;
this.y = y;
}
double getDistance(int x1, int y1) {
double res = 0.0;
res = Math.sqrt((x1-x)*(x1-x)+(y1-y)*(y1-y));
return res;
}
}
public class Exercise6_6 {
public static void main(String[] args) {
MyPoint p = new MyPoint(1, 1);
System.out.println(p.getDistance(2, 2));
}
}
6_7)
int weapon, int armor => 모든 병사의 공격력과 방어력은 같아야 하므로 static 변수로 정의
void weaponUp(), void armorUp() => static변수에 대한 작업을 하는 메서드이므로 static 메서드로 정의
* 보통 인스턴스 메서드는 인스턴스 변수와 관련된 작업을 , static메서드는 static변수와 관련된 작업
6_8)
2번 생성자는 객체를 초기화하기 위한 것, 객체 생성은 new 연산자
5번 생성자 오버로딩 가능
6_9)
2번 this는 static변수와 static메소드는 사용 불가
6_10)
3번, 4번 리턴타입과 매개변수의 이름은 메소드 오버로딩에 영향을 미치지 않는다
6_11)
2번, 3번, 4번
6_12)
3번 초기화 블럭이 수행된 후 생성자가 수행됨
5번 클래스가 처음 로딩될 때 클래스 변수가 초기화 되고 인스턴스가 생성될 때 인스턴스 변수가 초기화 된다
6_13)
1번
변수의 초기화 순서
(1) 인스턴스 변수 : 기본값 - 명시적 초기화 - 인스턴스 초기화블럭 - 생성자
(2) 클래스 변수 : 기본값 - 명시적 초기화 - 클래스 초기화블럭
'Study > Java' 카테고리의 다른 글
Chapter07.객체지향 프로그래밍2 (1) | 2023.07.09 |
---|---|
Chapter06.객체지향 프로그래밍1(2) (0) | 2023.07.09 |
03. 연산자 (0) | 2023.04.03 |
02. 변수 (0) | 2023.04.02 |
01. 자바 (0) | 2023.04.01 |
댓글