1. 클래스 간의 형변환

 

- 클래스 간에는 형변환이 안되지만 상속관계에 있는 클래스끼리는 형변환이 가능하다.

 

- 부모객체는 자식객체를 참조할수 있다.(업캐스팅) 하지만 자식객체에서 추가된 멤버는 접근할수없고, (오버라이딩된)메소드는 호출이 가능하다.

 

- 자식객체는 부모객체를 참조할수 있다. 단 이때는 자식타입으로 형변환 해야 한다.(다운캐스팅)

 

예)

byte a=100;
int b=a;        //가능

// 가능. 큰데이터형을 작은데이터형에 저장할때는 반드시 형변환해야 한다.
byte c=(byte)b;   

 

MyShape sh = new MyShape();
MyRect mr = new MyRect();
MyTriangle mt = new MyTriangle();


//부모객체는 자식객체를 참조할수 있다.
MyShape mm = mr;

 

//자식객체는 부모객체를 참조할수 있다. 단 이때는 자식타입으로 형변환해야 한다.
MyRect mr1 = (MyRect)mm;

 

ex>

class MyShape{

    private String color;

    public MyShape(String color)
    {
        this.color=color;
    }
    public String getColor()
    {
        return color;
    }
    public void draw(){}
}
class MyRect extends MyShape
{
    public MyRect(String color){
        super(color);
    }
    public void draw(){
        System.out.println(getColor() + "색상의 사각형을 그려요!");
    }
    public void move(){
        System.out.println("사각형을 이동하세요!");
    }
}
class Test01_reference
{
    public static void main(String[] args)
    {
        MyRect mr  = new MyRect("Red");

MyShape ms = mr;

ms.draw();

ms.getColor();

MyShape ms1 = new MyRect("Red");

ms1.draw();

ms1.getColor();

ms1.move(); //  오류 발생함. 자식만 존재하고 부모는 없기때문에

MyRect mr1 = (MyRect)ms;

mr1.move();

    }
}

 

 


2.  다형성(Polymorphism)

 

- 같은 종의 생물이지만 모습이나 고유한 특징이 다양한 성질을 갖는것

 예:오버로딩,오버라이딩,..

 

ex>

class MyShape{

    //도형색상
    private String color;    

    public MyShape(String color){
        this.color=color;
    }

    public String getColor(){
        return color;
    }

    //도형그리기기능
    public void draw(){   
    }
}
class MyRect extends MyShape
{
    public MyRect(String color){
        super(color);
    }

    //오버라이딩
    public void draw(){       
        System.out.println(getColor()+"색상의 사각형을 그려요!");
    }
    public void moveRect(){
        System.out.println("사각형을 이동해요!");
    }
}
class MyCircle extends MyShape
{
    public MyCircle(String color){
        super(color);
    }
    public void draw(){
        System.out.println(getColor()+"색상으로 타원을 그려요!");
    }
    public void moveCircle(){
        System.out.println("타원을 이동해요!");
    }
}
class Test02_polymorphism
{
    public static void main(String[] args)
    {
        MyRect mr=new MyRect("빨강");
        MyCircle mc=new MyCircle("파랑");

        //printer(mr);
        //printer(mc);

        printer1(mr);
        printer1(mc);
    }
    public static void printer(MyShape ms)
    {
        System.out.println("프린터로 아래 도형을 출력해요!");
        ms.draw();
    }
    public static void printer1(MyShape ms)
    {
        System.out.println("프린터로 아래 도형을 출력해요!");
        ms.draw();

        //ms가 MyRect타입의 객체냐?
        if(ms instanceof MyRect)
        {
            MyRect mm=(MyRect)ms;
            mm.moveRect();
        }
       
        //ms가 MyCircle타입의 객체냐?
        if(ms instanceof MyCircle)
        {
            MyCircle mm=(MyCircle)ms;
            mm.moveCircle();
        }
    }

//    public static void printer(MyRect mr){
//        System.out.println("프린터로 아래 도형을 출력해요!");
//        mr.draw();
//    }
//    public static void printer(MyCircle mc){
//        System.out.println("프린터로 아래 도형을 출력해요!");
//        mc.draw();
//    }
}

 

 

 

 

'JAVA' 카테고리의 다른 글

패키지  (0) 2014.09.12
추상 클래스 - 메소드 / 인터페이스 / Object  (0) 2014.09.12
오버라이딩 / final의 용도  (0) 2014.09.12
상속  (0) 2014.09.12
this  (0) 2014.09.12

 

1. 오버라이딩(**)

 

- 부모클래스의 메소드를 자식클래스에서 수정하고자 할때 오버라이딩을 한다.

- 만드는 방법 : 부모클래스의 메소드명,파라미터갯수,타입 모두 일치해야 한다.

 

예)

class AA{
     public void show(){...}
}
class BB extends AA{
    //오버라이딩
    public void show(){
          //수정할 내용;
   }

   //오버로딩
   public void show(int a){
           ..
   }
}

 

 

- 오버라이딩할때 접근지정자는 부모의 접근지정자보다 범위가 좁으면 안된다. 최소한 같거나 넓어야 한다.

 

 

[ 접근지정자 ]
private : 자신의 클래스내에서만 접근(자식클래스접근x)
default : (접근지정자를 쓰지 않은 경우)같은 패키지내에서만 접근 가능
protected : 같은 패키지내에서, 패키지가 달라도 자식클래스는 접근 가능
public : 어디서든 접근 가능

 

  
- 범위의 크기
  private < default < protected < public

 

 

ex>

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+",y좌표:"+y);
    }
}
class MyRect extends MyShape
{
    public MyRect(int x,int y){
        super(x,y);
    }
    //오버라이딩
    public void draw()
    {
        //부모에 있는 draw() 호출!
        super.draw();
        System.out.println(x+","+y+"의 좌표에 사각형을 그려요!");
    }

    //오버로딩!
    public void draw(String color)
    {
        System.out.println(color+"색상으로 " +x+","+y+
            "의 좌표에 사각형을 그려요!");
    }
    // 이미 존재한다고 오류 메시지 나옴.
    //public String draw(){//오류==>오버로딩도 오버라이딩도 아님!
    //    return x+","+y+"의 좌표에 사각형을 그려요!";
    //}
}

class Test06_Overriding
{
    public static void main(String[] args)
    {
        MyRect mr=new MyRect(100,200);
        mr.draw();//
    }
}

 

 

 


ex>

class MyShape
{
    private double x,y;
    public MyShape(double x,double y){
        this.x=x;this.y=y;
    }
    public double getX(){
        return x;
    }
    public double getY(){
        return y;
    }
}
class MyRect extends MyShape
{
    //부모가 파라미터를 갖는 생성자를 갖고 있다면
    // 자식생성자에서 부모생성자를 호출해
    // 파라미터를 넘겨 주어야 한다.!
    public MyRect(double x,double y){
        //부모생성자 호출!
        super(x,y);
    }
    public double getArea(){
         return getX()*getY();
    }
}
class Test07_inheritance
{
    public static void main(String[] args) {
        //MyShape sh=new MyShape(); ==> 오류
        MyRect mr=new MyRect(1,2);
        System.out.println("사각형넓이:"+mr.getArea());
    }
}

 

 

 

 


2.  final 의 용도

 

1. 변수앞에 final을 붙여서 상수로 만든다.
       final double PI=3.14;

 

2. 메소드앞에 final이 붙으면 ==> 오버라이딩 할 수 없다.

 

3. 클래스앞에 final이 붙으면 ==> 상속받을 수 없다.

 

ex>

final class  AA{
    //오버라이딩 불가!
    public final void show(){
        System.out.println("AA");
    }
}
class BB extends AA{
    //public void show(){ //오류 발생!
    //    System.out.println("BB");
    //}
}
class Test08_final{
    public static void main(String[] args){
       
    }
}

 

 

 

 

'JAVA' 카테고리의 다른 글

추상 클래스 - 메소드 / 인터페이스 / Object  (0) 2014.09.12
클래스간 형변환 / 다형성  (0) 2014.09.12
상속  (0) 2014.09.12
this  (0) 2014.09.12
객체배열  (0) 2014.09.12

 

1. 상속(**)

 

- 기본클래스(부모클래스,super클래스)의 속성과 메소드를 물려받고 기존의 기능을 수정하거나 새로운 기능을 추가(확장)하는 것

- 형식

class 부모클래스{
      ...
}
class 자식클래스 extends 부모클래스{
      ..
}

 

- 부모의 private멤버는 자식클래스에서 직접 접근할수 없다.

- 부모의 protected멤버는 외부(다른패키지)에서는 접근할 수 없고 자식클래스에서는 접근할 수 있다.

 

 

ex> 부모 : 이름, 주민번호 private 선언. 자식에서 바로 사용못함.

       메소드를 이용하여 변수에 값 set.

//부모클래스(super클래스)
class Person  
{
    //이름
    private String name;

    //주민번호
    private String snum;

    public void setPer(String name,String snum)
    {
        this.name=name;
        this.snum=snum;
    }
    public void printPer()
    {
        System.out.println("이름:"+name+",주민번호:"+snum);
    }
}
//자식클래스

class Student extends Person    
{
    //학번
    private int stuNum;

    public void setStu(String name,String snum,int stuNum){
        setPer(name,snum);
        this.stuNum=stuNum;
    }
    public void printStu(){
        printPer();
        System.out.println("학번:"+stuNum);
    }
}

class Test03_inheritance{
    public static void main(String[] args){
        Student stu=new Student();
        stu.setStu("홍길동","123456-1234567",987654);
        stu.printStu();
    }
}

 

 

 

 


- protected 멤버는 자식클래스에서 접근이 가능하다.

 

ex> 부모 : 이름과 주민번호는 protected 로 선언. 자식에서 사용가능.

//부모클래스(super클래스)

class Person          
{
    //이름
    protected String name;
    //주민번호
    protected String snum;

    public void setPer(String name,String snum)
    {
        this.name=name;
        this.snum=snum;
    }
    public void printPer()
    {
        System.out.println("이름:"+name+",주민번호:"+snum);
    }
}

 

//자식클래스

class Student extends Person
{
    //학번
    private int stuNum;

    public void setStu(String name,String snum,int stuNum)
    {
        this.name=name;
        this.snum=snum;
        this.stuNum=stuNum;
    }
    public void printStu(){
        System.out.println("이름:"+name);
        System.out.println("주민번호:"+snum);
        System.out.println("학번:"+stuNum);
    }
}

class Test04_inheritance
{
    public static void main(String[] args)
    {
        Student stu=new Student();
        stu.setStu("홍길동","123456-1234567",987654);
        stu.printStu();
    }
}

 

 

 

ex> 사각형, 삼각형 넓이 구하기.

class MyShape
{
    private double x,y;

    public void setXY(double x,double y)
    {
        this.x=x;this.y=y;
    }
    public double getX(){return x;}
    public double getY(){return y;}
}
class MyRect extends MyShape
{
    public double getArea()
    {
        double area=getX()*getY();
        return area;
    }
}
class MyTriangle extends MyShape
{
    public double getArea()
    {
        return getX()*getY()/2;
    }
}
class Test05_inheritance
{
    public static void main(String[] args)
    {
        MyRect mr=new MyRect();
        mr.setXY(10.0,20.0);
        System.out.println("사각형넓이:"+mr.getArea());

        MyTriangle mt=new MyTriangle();
        mt.setXY(10.0,20.0);
        System.out.println("삼각형넓이:"+mt.getArea());
    }
}

 

 

 

 

- 상속에서의 생성자

 

- 자식 객체가 생성될 때 부모 생성자가 호출되고 자신의 생성자가 호출된다!

 

ex>

class MyParent
{
    private int a;
    public MyParent(){

        System.out.println("나는 부모생성자");
    }
    public MyParent(int a){
        this.a=a;
    }
    public void printA(){
        System.out.println("a:"+a);
    }
}
class MyChild extends MyParent
{
    private int b;

    public MyChild(){
        //super();
        System.out.println("나는 자식생성자");
    }
    public MyChild(int a,int b){
        //부모생성자 호출!!!
        //위치는 가장 첫라인에 와야 함!
        super(a);
        this.b=b;
    }
    public void printB(){
        System.out.println("b:"+b);
    }
}
class  Test06_inheritance{
    public static void main(String[] args)
    {
        MyChild mc=new MyChild(1,2);
        mc.printA();
        mc.printB();

    }
}

 

 

 

 

 

'JAVA' 카테고리의 다른 글

클래스간 형변환 / 다형성  (0) 2014.09.12
오버라이딩 / final의 용도  (0) 2014.09.12
this  (0) 2014.09.12
객체배열  (0) 2014.09.12
static  (0) 2014.09.12

 

1. this

 

- 객체 자신을 의미(객체자신의 주소값)

 

- this의 용도

1) 멤버변수와 매개변수의 이름이 같을때 멤버변수앞에 this를 붙여서 구분
2) 다른 생성자를 호출할때
3) 객체자신을 메소드의 파라미터로 보낼때

 

ex>

class MyUser
{
    private String id;
    private String pwd;

 

    //다른 생성자 호출
    public MyUser(){
        this("admin","0000");
    }
    //멤버변수와 매개변수의 이름이 같을때 
    public MyUser(String id,String pwd)
    {
        this.id=id;
        this.pwd=pwd;
    }
    public void print(){
        System.out.println("아이디:"+id+",비밀번호:"+pwd);
    }
}
class  Test01_this
{
    public static void main(String[] args)
    {
        MyUser user1=new MyUser();
        user1.print();

        MyUser user2=new MyUser("song","1234");
        user2.print();
    }
}

 

ex>

class MyRect
{
    private String color;
    private int x,y;

    public MyRect(String color,int x,int y)
    {
        this.color=color;
        this.x=x;this.y=y;
    }
    public String getColor(){
        return color;
    }
    public int getX(){
        return x;
    }
    public int getY(){
        return y;
    }
    //객체자신을 메소드의 파라미터로 보낼때
    public void print(){
        Printer.prtPrint(this);
    }
}
class Printer
{
    public static void prtPrint(MyRect mr){
        System.out.println("프린터로 아래의 정보를 갖는 사각형을 출력");
        System.out.println("x:"+mr.getX() +",y:"+mr.getY()+",색상:"+ mr.getColor());
    }
}
class Test02_this
{
    public static void main(String[] args)
    {
        MyRect rr=new MyRect("빨강",100,200);
        rr.print();
    }   
}

 

 

 

 

 

'JAVA' 카테고리의 다른 글

오버라이딩 / final의 용도  (0) 2014.09.12
상속  (0) 2014.09.12
객체배열  (0) 2014.09.12
static  (0) 2014.09.12
final  (0) 2014.09.12

 

1.객체배열


ex> 객체배열 사용

class MyPerson

{

    private String name;

    private int age;


    public MyPerson(){}


    public MyPerson(String name,int age)

    {

        this.name=name;

        this.age=age;

    }

    public void setData(String name,int age)

    {

        this.name=name;

        this.age=age;

    }

    public void printInfo()

    {

        System.out.println("이름:"+name);

        System.out.println("나이:"+age);

    }

}


class Test09_ObjectArray

{

    public static void main(String[] args)

    {

        //MyPerson 객체가 3개 만들어지는 것이 아니라

        //MyPerson객체를 참조할수 있는 참조변수가 3개배열로 만들어지는것임

        MyPerson aa[]=new MyPerson[3];

        

        aa[0]=new MyPerson("이순신",20);

        aa[1]=new MyPerson("김유신",25);

        aa[2]=new MyPerson("강감찬",30);

 

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

        {

            aa[i].printInfo();

        }    

    }

}

 

 


ex> 3개 입력받아 객체배열에 저장하고 출력하는 예제

import java.util.Scanner;

 

class MyBook

{

    private String title;//책제목

    private int price;//가격

    public MyBook(){}

    public void setData(String title,int price)

    {

        this.title=title;

        this.price=price;

    }

    public String getTitle()

    {

        return title;

    }

    public int getPrice()

    {

        return price;

    }

}


class Test10_ObjectArray

{

    public static void main(String[] args)

    {

        //MyBook객체를 3개 저장하는 객체배열을 만들고 값을 저장후 출력해 보세요!

        MyBook []mb=new MyBook[3];

        mb[0]=new MyBook();

        mb[1]=new MyBook();

        mb[2]=new MyBook();

       // mb[0].setData("java",10000);

       // mb[1].setData("jsp",20000);

       // mb[2].setData("android",30000);

        Scanner scan=new Scanner(System.in);

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

        {

            System.out.print("도서제목:");

            String title=scan.next();

            System.out.print("가격:");

            int price=scan.nextInt();

            mb[i].setData(title,price);

        }

 

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

        {

            System.out.println("도서제목:"+ mb[i].getTitle());

            System.out.println("가격:"+mb[i].getPrice());

        }

    }

}

 

 


 

 

'JAVA' 카테고리의 다른 글

상속  (0) 2014.09.12
this  (0) 2014.09.12
static  (0) 2014.09.12
final  (0) 2014.09.12
Overloading  (0) 2014.09.12

+ Recent posts