형변환

1.기본형변환

     ----------자동형변환------------> 

byte->short / char->int->long->float->double
     <--------강제형변환-------------
             ex) float f=(float)1.2;

 

2.객체형변환

상속관계로 인해 존재(부모클래스 < 자식클래스)
1)자동 객체형변환

자식클래스에서 부모클래스로 자동형변환이 일어난다
2)명시적인 객체형변환

부모클래스에서 자식클래스로 자동형변환이 일어나지 않는다 => 명시적인 형변환을 해줘야한다

 

*instanceof 연산자

상속관계인지 여부를 확인시켜주는 연산자

형식) if (객체명 instanceof 클래스명)

객체가 이 클래스를 통해서 만들어진 객체라면 true반환 

/*
 * shape(부모)
 *    point
 *       line
 *          square(자식) 
 * */
public class ShapeTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Shape s = new Shape();
		Point p = new Point();
		Line l = new Line();
		Square sq = new Square();
		
        System.out.println("\n---객체자동형변환 전---");
		s.shapeDraw();
		p.pointDraw();
		l.lineDraw();
		sq.squareDraw();
		
		System.out.println("\n---객체자동형변환 후---");
		//형변환이 된다는 것은 자료형이 같다는 의미이다
		//배열 사용하기-> 같은 자료형만 저장된다
		Shape sh[]= new Shape[4]; //객체배열
		sh[0]=s;
		sh[1]=p;//부모형객체배열에 자식형객체를 담을 수 있다
		sh[2]=l;
		sh[3]=sq;
		
		for(int i=0;i<sh.length;i++) {
			sh[i].draw();//메소드는 동일하지만 객체가 달라 구분해서 호출가능
			whoAreYou(sh[i]);
		}
	}//main

		// 자식객체명 instanceof 부모클래스명 
		static void whoAreYou(Shape sh) {
			//Shape 
			if(sh instanceof Shape)
				System.out.println("i am Shape");
			else 
				System.out.println("i am not Shape");
			//Point
			if(sh instanceof Point)
				System.out.println("i am Point");
			else 
				System.out.println("i am not Point");
			//Line
			if(sh instanceof Line)
				System.out.println("i am Line");
			else 
				System.out.println("i am not Line");
			//Square
			if(sh instanceof Square)
				System.out.println("i am Square");
			else 
				System.out.println("i am not Square");
			
		}
	}

//Shape->Point->Line->Square
//Shape
class Shape{
	//모든 도형에 공통으로 사용하는 메소드 
	void draw() {
		System.out.println("Shape");
	}
	//Shape전용 메소드
	void shapeDraw() {
		System.out.println("Shape");
	}
}
//Point
class Point extends Shape{
	@Override
	void draw() {
		// TODO Auto-generated method stub
		System.out.println("Point");
	}
	void pointDraw() {
		System.out.println("Point");
	}
}
//Line 
//상속누적
class Line extends Point{
	@Override
	void draw() {
		// TODO Auto-generated method stub
		System.out.println("Line");
	}
	void lineDraw() {
		System.out.println("Line");
	}
}
//Square
class Square extends Line{
	@Override
	void draw() {
		// TODO Auto-generated method stub
		System.out.println("Square");
	}
	void squareDraw() {
		System.out.println("Square");
	}
}
/*
---객체자동형변환 전---
Shape
Point
Line
Square

---객체자동형변환 후---
Shape
i am Shape
i am not Point
i am not Line
i am not Square
Point
i am Shape
i am Point
i am not Line
i am not Square
Line
i am Shape
i am Point
i am Line
i am not Square
Square
i am Shape
i am Point
i am Line
i am Square
*/

 

명시적 형변환 예시

public class ButtonTest2 extends JFrame implements ActionListener{
	
	JButton b1,b2,b3,b4;
	JTextField tf1;
	
	public ButtonTest2() {
		super("버튼의 이벤트처리");
		setBounds(900, 300, 400, 300);
		this.setLayout(new GridLayout(5,1,3,3));
		
		//버튼객체생성
		b1=new JButton("시작");
		b2=new JButton("고");
		b3=new JButton("백");
		b4=new JButton("점프");
		tf1=new JTextField(" ");
		
		//버튼을 컨테이너에 부착
		this.add(b1); add(b2); add(b3); add(b4); add(tf1);
		
		b1.addActionListener(this);
		b2.addActionListener(this);
		b3.addActionListener(this);
		b4.addActionListener(this);
		tf1.addActionListener(this);
		
		this.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				// TODO Auto-generated method stub
				System.exit(0);			}
		});
		setVisible(true);
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		System.out.println(e.getActionCommand());
		String s = e.getActionCommand();
		
		//추가+++) 이벤트를 발생시킨 컴포넌트의 종류=> e.getSource()
		Object o = e.getSource();//JButton or JTextField
		if(o instanceof JButton) {//이벤트발생시킨 컴포넌트가 버튼이라면
			JButton b =(JButton)o;//자식형객체=(자식형)부모객체 //명시적인 형변환의 예시 
			if(s.contentEquals("시작")) {//시작버튼 눌렀다면
				b.setBackground(Color.red);
				setTitle(s);//창의 제목에 버튼이름 찍힘
			}else if(s.contentEquals("고")) {
				b.setBackground(Color.yellow);
				setTitle(s);
			}else if(s.contentEquals("백")) {
				b.setBackground(Color.blue);
				setTitle(s);
			}else if(s.contentEquals("점프")) {
				b.setBackground(Color.orange);
				setTitle(s);
			}
		}else {//if(o instanceof JTextField)
			JTextField tf2=(JTextField)o;
			//텍스트필드에 글자쓰기(setText), 글자써진걸 받아오기(getText)
			tf2.setText("객체형변환");
			setTitle(tf2.getText());//tf2.setText(""):글자지우고 싶은 경우
		}
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new ButtonTest2();
	}
}

 

결과창

 

 

+ Recent posts