1. 상속과 생성자함수
(1) 예제 1 : 소스코드, 실행결과, 주석(A,B,C 클래스 중 이유)
class A{
public A(){
System.out.println("생성자 A");
}
}
class B{
public B(){
System.out.println("생성자 B");
}
}
class C{
public C(){
System.out.println("생성자 C");
}
}
public class testfifthseven {
public static void main(String[] args) {
//C 클래스의 c객체 생성
C c = new C();
//실행결과 생성자 C 라고 나오며 그 이유는 C 클래스는 외부로 부터 상속을 받은 것이 없기 때문임.
}
}
(2) 예제 2 : A,B,C 클래스가 상속관계에 있을 때 소스코드, 실행결과, 주석(실행결과가 나온 이유)
클래스들이 상속관계에 있을 경우 클래스 내의 생성자들의 우선순위는 서브 클래스의 생성자가 실행되기 전 슈퍼 클래스의 생성자가 먼저 실행된다.
(3) 예제 3 : 명시적 호출 예제 소스코드, 실행결과, 주석(명시적 호출방법, super() 주의점)
class A{
public A(){ //
System.out.println("생성자 A");
}
public A(int x){ //
System.out.println("매개변수 있는 생성자 A");
}
}
class B extends A{
public B(){ //
System.out.println("생성자 B");
}
public B(int x){ //
super(x); //상위클래스에 매개변수가 있는 생성자를 명시적으로 호출함
System.out.println("매개변수 있는 생성자 B");
}
}
class C extends B{
public C(){ //
System.out.println("생성자 C");
}
}
public class testfifthseven {
public static void main(String[] args) {
//C 클래스의 c객체 생성
B b = new B(5); // B클래스의 객체 생성
/* 클래스의 상속간에 기본 생성자가 아닌 매개변수가 있는 생성자를 호출 하기 위해서 명시적 호출방법이 필요하다. 매개변수가 있는 생성자 내에 super() 명령어를 사용하면 매개 변수를 가진 슈퍼 클래스의 생성자를 호출할 수 있다. 이때 super() 명령어의 주의점으론 반드시 해당 생성자의 첫 라인에 와야한다. */
}
}
(4) 예제 4 : 프로그램 5-2 소스코드, 실행결과, 주석(결과에서 cp객체가 5,6,blue값을 전달하는데 왜 blue(5,6)으로 나왔는지에 대한 이유)
class Point{
private int x, y;
Point(){
this.x = this.y = 0;
}
Point(int x, int y){
this.x = x; this.y = y;
}
void showPoint(){
System.out.println("(" + x + "," + y + ")");
}
}
class ColorPoint extends Point {
private String color;
ColorPoint(int x, int y, String color){
super(x,y);
this.color = color;
}
void showColorPoint(){
System.out.print(color);
showPoint();
}
}
public class SuperEx{
public static void main(String[] args){
ColorPoint cp = new ColorPoint(5, 6, "blue");
cp.showColorPoint();
/*
5,6,blue를 매개변수로 전달 하는 과정에서 5,6은 상속받은 상위 클래스의
매개변수 생성자로 넘어가고 color는 ColorPoint 클래스 내에서 private
접근 지정자의 color에 들어가고 showPoint 함수에 의하여 불러오게 된다.
*/
}
}
2. 업캐스팅
(1) 개념 : 서브 클래스 객체가 슈퍼 클래스 타입으로 변환되는 것을 업캐스팅 이라고 한다.
(2) 예제 : 소스코드, 실행결과, 주석(업캐스팅이 적용된 설명)
class Person{
String name;
String id;
public Person(String name) {
this.name = name;
}
}
class Student extends Person{
String grade;
String department;
public Student(String name) {
super(name);
}
}
public class test513 {
public static void main(String[] args) {
Person p;
Student s = new Student("홍길동");
p = s;
/*
Person 클래스의 p 객체에 Student 클래스의 s 객체를
업캐스팅 시킴
*/
System.out.println(p.name);
/*
그래서 p의 이름을 호출하였는데 s의 값이 p에 치환되서 s의 이름이
출력이 된다.
*/
s.grade = "A";
s.department = "컴퓨터";
System.out.println("등급 : " + s.grade);
System.out.println("학과 : " + s.department);
}
}
'basic > Java 8' 카테고리의 다른 글
[Java] Exception (0) | 2018.08.07 |
---|---|
4. 클래스와 객체 (0) | 2017.04.11 |
3. 반복문과 배열 그리고 예외처리 (0) | 2017.03.31 |
2. 자바 기본 프로그래밍 (0) | 2017.03.14 |
1. 자바시작 (0) | 2017.03.07 |