<클래스1-student1>
public class Student1 {
private String stuName;
private String hp;
private int score;
public Student1() {
this("홍길동", "010-4444-6666", 100);
}
//같은 생성자끼리는 this()로 서로 호출 가능
//반드시 첫줄에 써주기
public Student1(String name, String hp) {
this(name,hp,0);
//아래에 쓴 거 가져오겠다는 의미
}
//멤버를 모두 인자로 가진 생성자
public Student1(String name, String hp, int score) {
this.stuName=name;
this.hp=hp;
this.score=score;
}
//전체출력메서드
public void getData() {
System.out.println("이름: "+this.stuName);
System.out.println("핸드폰 번호: "+this.hp);
System.out.println("점수: "+this.score);
}
<클래스2-StudentArrEx6>
public class StudentArrEx6 {
public static void main(String[] args) {
//student1으로 배열 생성
Student1[] stu=new Student1[3];
stu[0]=new Student1();
stu[1]=new Student1("이민아", "010-7777-8888", 90);
stu[2]=new Student1("송혜교", "010-1234-5678");
//배열로 출력
for(int i=0;i<stu.length;i++)
{
Student1 s=stu[i];
s.getData();
System.out.println("--------------");
}
//결과
이름: 홍길동
핸드폰 번호: 010-4444-6666
점수: 100
--------------
이름: 이민아
핸드폰 번호: 010-7777-8888
점수: 90
--------------
이름: 송혜교
핸드폰 번호: 010-1234-5678
점수: 0
--------------
~~~~~~~~~~~~~~~~~~~~
(예제)
class shop{
private String sangpum;
private int price;
private String color;
//명시적 생성자
public shop(String sangpum,int price,String color) {
this.sangpum=sangpum;
this.price=price;
this.color=color;
}
//제목 메서드
public static void showTitle() {
System.out.println("상품명\t단가\t색상");
System.out.println("==============");
}
//출력메서드
public void getData(){
System.out.println(sangpum+"\t"+price+"\t"+color);
}
}
public class ClassArrayEx7 {
public static void main(String[] args) {
shop[] sh=new shop[4];
//sh[0].getSangpum(); /NullPointException 발생(초기값 모두 널)
sh[0]=new shop("청바지", 25000, "블루");
sh[1]=new shop("브이넥티", 10000, "화이트");
sh[2]=new shop("면바지", 40000, "베이지");
sh[3]=new shop("블라우스", 60000, "노랑");
//출력
shop.showTitle();
for(int i=0;i<sh.length;i++)
{
shop s=sh[i];
s.getData();
}
//결과
상품명 단가 색상
==============
청바지 25000 블루
브이넥티 10000 화이트
면바지 40000 베이지
블라우스 60000 노랑
'JAVA' 카테고리의 다른 글
210813_오버로딩 (0) | 2021.08.13 |
---|---|
210812_call by (0) | 2021.08.12 |
210812_클래스+계산(예제) (0) | 2021.08.12 |
210812_클래스(예제) (0) | 2021.08.12 |
210812_클래스+this(예제) (0) | 2021.08.12 |