본문으로 바로가기

class human{

void showInfo() {

System.out.println("All human beings are equal.");

}

}

class Asian extends human{

}

public class Appilcation {


public static void main(String[] args) {

// TODO Auto-generated method stub

Asian test = new Asian();   객체를 생성함

test.showInfo(); human클래스의 showInfo메소드 호출

}}

실행결과  "All human beings are equal. 출력


오버라이딩은 부모 클래스(human) showInfo메소드를 물려받은 자식 Asian 클래스에서

반환타입, 메소드이름, 인수와 똑같은 기능을 하게 된다. 결국 덮어쓰게 되는 셈이다.


class Human{

void showInfo() {

System.out.println("All human beings are equal.");

}

}

class Asian extends Human{

void showInfo() {

System.out.println("longdi is an asian.");

}

}

public class Appilcation {


public static void main(String[] args) {

// TODO Auto-generated method stub

Human(부모클래스이름) test = new Asian(자식클래스이름)(); 

//이렇게 되면 자식클래스의 메소드가 호출된다. 단. 부모클래스의 메소드와 자식클래스의 메소드가 같을때 뒷부분이 출력된다.

이런것을 다형성이라고 한다

 

test.showInfo();

}}


출력결과 : 뒷쪽부분이 호출 longdi is an asian


class Human{

void showInfo() {

System.out.println("All human beings are equal.");

}

}

class Asian extends Human{

void showInfo() {

System.out.println("longdi is an asian.");

}

  void greeting()

{

}

}

public class Appilcation {


public static void main(String[] args) {

// TODO Auto-generated method stub

Human(부모클래스이름) test = new Asian(자식클래스이름)(); 

//이렇게 되면 자식클래스의 메소드가 호출된다. 단. 부모클래스의 메소드와 자식클래스의 메소드가 같을때

즉 Human이라는 타입은 Asian객체를 생성했다고 볼수 있겠다. 

타입은 옵션에 의한 메소드를 결정하는것이다.


test.greeting();// 컴파일에러 발생 왜냐하면 Human이라는 부모클래스에서 자식클래스의 greeting()메소드가 있지 않기 때문

}}


반대의 경우는 가능


class Human{

void showInfo() {

System.out.println("All human beings are equal.");

}

void talk() {

System.out.println("say someting");

}

}

class Asian extends Human{

void showInfo() {

System.out.println("longdi is an asian.");

}

void greeting()

{

System.out.println("Hello.");

}

}

public class Appilcation {


public static void main(String[] args) {

// TODO Auto-generated method stub

Asian test = new Asian();

test.talk();  //  Human클래스에서 자식클래스인 Asian에게 상속받았기 때문에 talk()메소드를 실행가능

}}


캡슐화




public class Phone {

private long number = 1231231234;  /// 외부에서 함부로 접근못하도록 제한하는 기능을 캡슐화라고 부른다.


public long getNumber() {

return number;   ---> 호출된 곳으로 반환

}


public void setNumber(long number) {

this.number = number;

}

}

public class Appilcation {

public static void main(String[] args) {
// TODO Auto-generated method stub
Phone myPhone = new Phone();
System.out.println(myPhone.getNumber());  //여기서 호출되어 출력
System.out.println("===================");
myPhone.setNumber(456456456);// Phone클래스에서 바꾸는것이 아니라 setter를 통해 전화번호를  다시 설정한다.
System.out.println(myPhone.getNumber());
System.out.println("===================");
}}



super

오버라이딩 하는 경우 부모클래스의 메소드도 이용하고 싶을 경우, super를 이용하면 됩니다.


class Human{

void showInfo() {

System.out.println("All human beings are equal.");

}

void talk() {

System.out.println("say someting");

}

}

class Asian extends Human{  //Asian 클래스는 Human클래스로부터 상속을 받았다. 

void showInfo() {

System.out.println("longdi is an asian.");

}

void greeting()

{

super.showInfo();  //만일 부모클래스의 showInfo메소드를 출력하고 싶으면 super를 이용해서 출력할수 있다.

System.out.println("Hello.");

}

}

public class Appilcation {


public static void main(String[] args) {

// TODO Auto-generated method stub

Asian asian1 = new Asian();

asian1.greeting();

}}


실행결과


final 붙이기

예를 들어서 슈퍼 클래스의 메소드 중에서는 서브 클래스에서 오버라이딩되면 안 되는 메소드가 있을 수 있다.

이런 경우, 슈퍼 클래스의 메소드 앞에 final을 붙이면 오버라이딩되지 않도록 막을 수 있다. 


final은 더이상 수정 할 수 없음이라는 의미를 나타내는 제한자이다. 

public class Phone {

private long number = 1231231234;

public static final String model = "dsfsd10939479";  // 절대로 수정할 수 없음 static을 선언했기 때문에

public long getNumber() {

return number;

}


public void setNumber(long number) {

this.number = number;

}

}



object 클래스 상속



java에서는  클래스를 만들때 슈퍼 클래스를 지정하지 않으면 그 클래스는 object클래스를 상속받는다


즉 , 아무것도 상속받지 않으면 object클래스를 상속받는 서브 클래스가 된다는 것


object클래스---  car클래스



object클래스--- Car클래스 ----Racing클래스



object클래스의 주요 메소드

메소드 

기능 

boolean equals(object obj) 

해당 객체가 인수로 전달된 객체와 동일한지 여부 판단 

class getClass() 

해당 객체의 클래스를 반환 

String toString() 

객체를 나타내는 문자열 반환 



toString() 메소드


객체를 나타내는 문자열 반환하는 기능



System.out.println(car1); car1가 출력될때, toString() 메소드가 호출

스스로 설계 한 클래스에서 toSting()메소드를 재정의해두면 매우 유용하다 


// 자동차 클래스


class Car


{

    

protected int num;

    

protected double gas;

    

    


public Car()

    

{

        

num = 0;

        

gas = 0.0;

        

System.out.println("자동차가 만들어졌습니다.");

    

}

    

public void setCar(int n, double g)

    

{

        

num = n;

   gas = g;

        

System.out.println("차량 번호를 " + num + "으로, 연료 양을 " + gas + "로 바꾸었습니다.");

    

}

    

public String toString() toString()메소드를 정의한다.

    

{

        

String str = "차량 번호 : " + num + " 연료 양 : " + gas; 

return str;

    

}


}




class Sample7


{

    

public static void main(String[] args)

    

{

        

Car car1 = new Car();

        

car1.setCar(1234, 20.5);

        

        


System.out.println(car1); toSring()메소드의 반환값이 사용된다.

    

}


}


실행결과

자동차가 만들어졌습니다.

차량 번호를 1234으로, 연료 양을 20.5로 바꾸었습니다.

차량 번호 : 1234 연료 양 : 20.5


equals()메소드 사용


두 변수가 가리키는 객체가 동일한 경우 true를 반환


class Car


{

    

protected int num;

    

protected double gas;

    

    


public Car()

{


        num = 0;

        

gas = 0.0;

        

System.out.println("자동차가 만들어졌습니다.");

    

}


}



class Sample8


{

    

public static void main(String[] args)

    

{

        

Car car1 = new Car();  car1과 car2는 서로 다른 객체

        

Car car2 = new Car();

        

        

Car car3;

        

car3 = car1; car1과 car3은 같은 객체

        

        


boolean bl1 = car1.equals(car2);

        

boolean bl2 = car1.equals(car3);

        

        


System.out.println ("car1과 car2가 같은지 조사한 결과, " + bl1 + "이었습니다.");

        

System.out.println ("car1과 car3이 같은지 조사한 결과, " + bl2 + "이었습니다.");

    

}


}


실행 결과


자동차가 만들어졌습니다.

자동차가 만들어졌습니다.

car1과 car2가 같은지 조사한 결과, false이었습니다.

car1과 car3이 같은지 조사한 결과, true이었습니다.




getClass()메소드


객체가 속한 클래스의 정보 확인


// 자동차 클래스


class Car


{

    

protected int num;

    

protected double gas;

    

    


public Car()

{

num = 0;

        

gas = 0.0;

        

System.out.println("자동차가 만들어졌습니다.");

    

}


}


// 레이싱 카 클래스


class RacingCar extends Car


{

    

private int course;


    

    

public RacingCar()

    

{

        

course = 0;

        

System.out.println("레이싱 카가 만들어졌습니다.");

    

}


}



class Sample9


{

    

public static void main(String[] args)

    

{

        

Car[] cars;

        

cars = new Car[2];

        

        


cars[0] = new Car();   첫번째 객체는 Car클래스

        

cars[1] = new RacingCar(); 두번째 객체는 Racing Car클래스

        

        


for(int i=0; i<cars.length; i++){

            

Class cl = cars[i].getClass(); 클래스 정보를 반환

            

System.out.println((i + 1) + "번째 객체의 클래스는 " + cl + "입니다.");

        

}

    

}


}


실행결과

자동차가 만들어졌습니다.

자동차가 만들어졌습니다.

레이싱 카가 만들어졌습니다.

1번째 객체의 클래스는 class Car입니다.

2번째 객체의 클래스는 class RacingCar입니다.