Web Developer/JAVA II
1. JAVA 2 - Class (클래스) 예제 및 연습문제
sayitditto
2023. 1. 10. 16:29
I. 예제
1) CellphoneTest
public class CellphoneTest {
public static void main(String[] args) {
// 나의 의식
Cellphone cp1 = new Cellphone ();
cp1.maker = "Apple";
cp1.model = "14pro";
cp1.color = "deep purple";
cp1.price = 170;
System.out.println(cp1.maker);
System.out.println(cp1.model);
System.out.println(cp1.color);
System.out.println(cp1.price);
cp1.call();
cp1.camera();
// field 값 변경하기
cp1.color = "light pink";
cp1.model = "14";
System.out.println(cp1.maker);
System.out.println(cp1.model);
}
}
2) Cellphone
// 설계도
public class Cellphone {
// 속성: member 변수 또는 field - 명사로 짓는 편
String maker;
String model;
String color;
int price;
// 기능: method
public void call() {
System.out.println("여보세요");
}
public void camera() {
System.out.println("찰칵");
}
}
II. 연습문제
1) PersonTest
public class PersonTest {
public static void main(String[] args) {
Person p1 = new Person ();
p1.name = "Stella";
p1.bday = "19960923";
p1.gender = "Female";
p1.sayhi();
p1.walk();
p1.introduce();
p1.printAge();
}
}
2) Person
public class Person {
// 속성: 멤버 변수 또는 field
String name;
String bday;
String gender;
// 기능: method
public void sayhi () {
System.out.println("안녕하세요~~ ");
}
public void walk () {
System.out.println("걷기 ");
}
public void introduce () {
System.out.println("내 이름은 " + this.name + "이고 성별은 " + this.gender);
}
public void printAge () {
int year = Integer.parseInt(bday.substring(0, 4));
int age = 2023 - year + 1;
System.out.println("나이는 " + age + "입니다 " );
}
}