7일차 : 오버로딩, 오버라이딩, 상속
상속 - Person객체, Student 객체 생성하여 이름, 주민번호, 학번 출력하기
class Person{ private String name;//멤버변수 private String jumin; public Person(){ System.out.println("Person객체 생성");//생성자 } public void setPerson(String name, String jumin){//매개변수 this.name=name; this.jumin=jumin; } public void showPerson(){//출력하는 메소드 System.out.println("이름: "+name); System.out.println("주민번호: "+jumin); } } class Student extends Person{//Person클래스 상속받기. private String stuNum;//학번 public Student(){ System.out.println("Student객체 생성");//생성자 } public void setStudent(String name, String jumin, String stuNum){ //자식클래스라도 private멤버는 직접 접근할 수 없다. //this.name=name; //this.jumin=jumin; //부모 메소드를 통해서 간접적으로 멤버변수를 사용한다. setPerson(name, jumin);//private을 사용하면 접근이 불가능하다. 그러나 펄슨 메소드를 불러오면 간접적으로 접근이 가능하다? this.stuNum=stuNum; } public void showStudent(){ showPerson(); System.out.println("학번: "+stuNum); } } class Inheritance01{ public static void main(String[] args) { Student stu=new Student(); stu.setStudent("홍길동", "801212-5678123", "0212345"); stu.showStudent(); } } /* 결과 Person객체 생성 Student객체 생성 이름: 홍길동 주민번호: 801212-5678123 학번: 0212345 */
상속 - 부피값 구하기
/* 부모 클래스가 생성자를 갖는 경우 - 부모 생성자에서 파라미터를 받아야 하는 경우에 자식 생성자에서 반드시 super()로 부모 생성자를 호출하여 파라미터를 전송해야 한다. super()는 자식생성자 제일 첫 라인에 와야 한다. */ class MyRect{ protected double x; //가로길이 protected double y; //세로길이 public MyRect(double x, double y){//부모생성자의 파라미터 값을 무조건 넣어주는 작업을 해줘야 한다. this.x=x; this.y=y; } public double getArea(){return x*y;} } class ChildRect extends MyRect{ private double h; public ChildRect(double x, double y, double h){//반드시 자식생성자에서 부모생성자를 호출하는 값을 넣어주어야 한다. super(x,y);//부모 생성자 호출하기! (double x, double y) this.h=h; } public double getVolume(){return getArea()*h;} } class Inheritance02{ public static void main(String[] args) { ChildRect rr=new ChildRect(2,3,4); System.out.println("부피: "+rr.getVolume()); } } /* 결과 부피: 24.0 */
오버라이딩 - x,y의 값 구하기
class Rect{ protected int x,y; public Rect(int x, int y){ this.x=x; this.y=y; } public void print(){ //출력해주는 메소드...이지만 오버라이딩으로 인해 오버라이딩 부분이 출력이 된다. System.out.println("x: "+x); System.out.println("y: "+y); } } class ChildRect extends Rect{ private int z; public ChildRect(int x, int y, int z){ super(x,y); this.z=z; } public void print(){ //오버라이딩(수정, 덮어씌우기)- 이렇게 수정, 덮어씌워줬으니 24~16행에 덮어씌워지고 이부분으로 출력이 되는 것이다. super.print(); //부모클래스의(와 자식클래스가 똑같아 구분하기 힘든 경우) print메소드 호출 System.out.println("x: "+x); System.out.println("y: "+y); System.out.println("z: "+z); } public void print(int a) { //오버로딩 -추가되는 개념 } } class Overriding01{ public static void main(String[] args) { ChildRect rr=new ChildRect(2,3,4); rr.print(); //누가 호출??? 자식이있는 메소드로 호출 rr.print(10); } } /* 결과 x: 2 y: 3 x: 2 y: 3 z: 4 */
오버라이딩 - 삼각형, 사각형 넓이 각각 구하기
class Shape{ protected int x,y; public Shape(int x, int y){ this.x=x; this.y=y; } public int getArea(){return 0;} } class MyRect extends Shape{ public MyRect(int x, int y){ super(x,y);//부모생성자 호출 } public int getArea(){ //오버라이딩 return x*y; } } class MyTri extends Shape{ public MyTri(int x, int y){ super(x,y); } public int getArea(){ //오버라이딩 return (x*y)/2; } } class Overriding02 { public static void main(String[] args) { MyRect rr=new MyRect(1,2); System.out.println("사각형넓이: "+rr.getArea()); MyTri tri=new MyTri(10,3); System.out.println("삼각형넓이: "+tri.getArea()); } } /* 결과 사각형넓이: 2 삼각형넓이: 15 */
오버라이딩, 클래스간의 형변환 - 사각형, 삼각형의 넓이 각각 구하기
class Shape{ protected int x,y; public Shape(int x, int y){ this.x=x; this.y=y; } public int getArea(){return 0;} } class MyRect extends Shape{ public MyRect(int x, int y){ super(x,y);//부모생성자 호출 } public int getArea(){ //오버라이딩 return x*y; } public void printArea(){ System.out.println("x:"+x+"y:"+y); System.out.println("사각형넓이:"+getArea()); } } class MyTri extends Shape{ public MyTri(int x, int y){ super(x,y); } public int getArea(){ //오버라이딩 return (x*y)/2; } } class Overriding03{ public static void main(String[] args) { MyRect rr=new MyRect(10,20); //부모클래스는 자식클래스를 참조할 수 있다. shape:부모 Shape sh=rr; //쉐이프에 저장되어있는건 MyRect //부모클래스타입으로 호출하지만 자식에서 (오버라이딩 된) 메소드가 호출된다. int area=sh.getArea(); System.out.println("사각형의 넓이: "+area); //sh.printArea(); //오류발생-->부모타입으로는 자식에서 추가된 멤버는 참조못함. MyRect r1=(MyRect)sh; //자식클래스가 부모클래스를 참조할 때는 (형변환)해야 함. 왜! 부모클래스가 더 크니까. MyTri tri=new MyTri(30,40); Shape sh1=tri; //? System.out.println("삼각형의 넓이: " +sh1.getArea()); } }
오버라이딩 - 도형의 넓이 구하기 --------------보류 (오류남/수정예정)
class Overriding04 {
public static void main(String[] args) {
MyRect rr=new MyRect(1,2);
MyTri tri=new MyTri(3,4);
printer(rr);
printer(tri);
}
//MyRect, MyTri 는 Shape의 자식클래스이므로 Shape타입의 매개변수 사용 가능!
public static void printer(Shape ss){
//getArea()메소드는 자식에서 오버라이딩되었으므로 부모를 통해 호출 가능!
System.out.println("도형의 넓이: "+ss.getArea());
//ss가 MyRect타입인 경우 printArea()메소드를 호출해 보세요~
}
if(ss instanceof MyRect){
MyRect rr=(MyRect)ss;
ss.PrintArea();
rr.printArea();
}
}
/*
public static void printer(Object ss){ //자바에는 최상의 클래스로 오브젝트가 있다. 부모. 5,6행이 올 수 있다.
if(ss instanceof MyRect){ //ss가 MyRect타입의 인스턴스(객체)인가? ss를 MyRect로 바꿔라.
MyRect rr=(MyRect)ss; //ss를 자식으로 형변환하기
System.out.println("사각형의 넓이: "+rr.getArea());
} else if (ss instanceof MyTri){ //ss가 MyTri타입의 인스턴스(객체)인가?
MyTri tt=(MyTri)ss;
System.out.println("삼각형의 넓이: "+tt.getArea());
}
}
*/
/*
public static void printer(MyRect rr){
System.out.println("사각형넓이: "+rr.getArea()+"를 프린터로 출력");
}
public static void printer(MyTri rr){
System.out.println("삼각형넓이: "+rr.getArea()+"를 프린터로 출력");
}
*/
}
/*
결과
도형의 넓이: 2
도형의 넓이: 6
*/
this
/*
<< this >>
- 객체자신을 의미(this는 객체자신의 주소값)
- 사용되는 경우
1) 멤버변수이름과 매개변수의 이름이 같을 때 멤버변수 앞에 this를
붙여 구분한다.
2) 다른 생성자를 호출할 때
3) 객체자신을 파라미터로 전달할 때
*/
class MyClass01{
private String name;
public MyClass01(String name){
this(); //다른 생성자 호출
this.name=name;
}
public MyClass01(){
System.out.println("객체가 생성됨");
}
public void print(){
System.out.println("name: "+name);//this가 생략되어 있는 것
}
}
class ThisTest01{
public static void main(String[] args) {
MyClass01 aa=new MyClass01("홍길동");//객체생성하기
aa.print();
MyClass01 bb=new MyClass01("김아무");
bb.print();
}
}
/*
[결과]
객체가 생성됨
name: 홍길동
객체가 생성됨
name: 김아무
*/
this - 프린터 출력
class MyBook { private String title; private int price; public MyBook(String title, int price){ this.title=title; this.price=price; } public String getTitle(){return title;} public int getPrice(){return price;} public void showInfo(){ //MyBook이라는 정보를 프린트나 데이터로 출력 Printer.print(this); //출력하고자 하는 자기 자신의 정보를 this로 주었다. 여기에서의 this는 bb=100번지 //print pp=new printer(); //pp.print(this); //아래 프린터에 static를 써주지 않으면 이렇게 출력해줘야 한다. } } class Printer{ public static void print(MyBook book){ // System.out.println("아래의 내용을 프린터로 출력합니다."); System.out.println(book.getTitle()+","+book.getPrice()); } } class ThisTest02{ public static void main(String[] args) { MyBook bb=new MyBook("JAVA",10000); bb.showInfo(); } } /* 결과 아래의 내용을 프린터로 출력합니다. JAVA,10000 */
Quiz01
//사각형의 넓이를 구하는 클래스 class MyRect{ private double x; //가로길이 //멤버변수 private double y; //세로길이 public void setX(double x){this.x=x;} public void setY(double y){this.y=y;} public double getX(){return x;} public double getY(){return y;} public double getArea(){return x*y;} } //위의 클래스를 상속받아 부피(가로*세로*높이)를 구하는 기능이 추가되는 자식클래스를 만들고 //main메소드를 사용해 보세요. class Rect extends MyRect{ //MyRect클래스 상속받기 private double h; //높이 public void setData(double x, double y, double h){ //파라미터 //부모 메소드를 통해서 간접적으로 멤버변수를 사용한다. setX(x); //4행을 불러온다 setY(y); //5행을 불러온다 this.h=h; } public double getVolume(){ return getX()*getY()*h; } } class Quiz01 { public static void main(String[] args) { //상속받은 MyRect클래스를 실행시키는 메인클래스 Rect rr=new Rect(); rr.setData(10,20,30); //임의의값을 넣어서 계산 System.out.println("부피 :"+rr.getVolume()); } }
Quiz02
class Person { private String name; private String jumin; public Person(String name, String jumin){ this.name=name; this.jumin=jumin; } public void showPerson(){ //출력하는 메소드 System.out.println("이름: "+name); System.out.println("주민번호: "+jumin); } } class Student extends Person{ private String stuNum; //학번 public Student(String name, String jumin, String stuNum){ //자식생성자에서 반드시 부모생성자를 호출하면서 파라미터를 전송해야 함 super(name, jumin); //부모 생성자를 호출 this.stuNum=stuNum; } public void showStudent(){ showPerson(); System.out.println("학번: "+stuNum); } } //Person클래스를 상속받는 Student클래스를 만들어 보세요. //Student클래스는 학번이 추가된다. class Quiz02{ public static void main(String[] args) { Student stu=new Student("홍길동", "801212-56781234", "0212345");//자식으로 따라가서 Student stu.showStudent(); } } /* 결과 이름: 홍길동 주민번호: 801212-56781234 학번: 0212345 */
Quiz03
class MyShape{ protected int x, y; public MyShape (int x, int y){ this.x=x; this.y=y; } public void draw(){ System.out.println("x좌표: "+x); System.out.println("y좌표: "+y); } } class MyLine extends MyShape{ public MyLine(int x, int y){ super(x,y);//생성자를 호출 } public void draw(){ //오버라이딩 super.draw();//부모클래스 메소드 호출 System.out.println("위의 좌표에 사각형을 그려요."); } } class MyRect extends MyShape{ public MyRect(int x, int y){ super(x,y); } public void draw(){ //오버라이딩 super.draw();//부모클래스 메소드 호출 System.out.println("위의 좌표에 직선을 그려요."); } } /* 위의 클래스를 상속받는 MyRect, MyLine의 클래스를 만들고 draw()라는 메소드를 오버라이딩 해보세요. [출력결과] x좌표: 10 y좌표: 100 위의 좌표에 사각형을 그려요. x좌표: 40 y좌표: 80 위의 좌표에 직선을 그려요. */ class Quiz03 { public static void main(String[] args) { MyShape sh=new MyRect(2,4); //가능! (부모가 자식개체를 참조할 수 있다) sh.draw(); //다형성 sh=new MyLine(6,7); //가능! sh.draw(); MyLine aa=(MyLine)sh;//자식이 부모를 참조할 때는 형변환!! /* MyLine rr=new MyLine(10, 100); rr.draw(); MyRect aa=new MyRect(40, 80); aa.draw(); */ } }
[ 과 제 ]
'JAVA 기초' 카테고리의 다른 글
9일차 : ArrayList, Character, String클래스, String Builder, Wrapper 클래스 (0) | 2012.08.11 |
---|---|
8일차 : 추상클래스, 인터페이스, Object클래스 (0) | 2012.08.11 |
6일차 : 오버로딩, final, static메소드 (0) | 2012.08.11 |
5일차 : 객체지향 프로그래밍, 생성자, 사용자 정의 메소드 (0) | 2012.08.05 |
4일차 : 배열 (0) | 2012.08.05 |