1. 패키지

 

- 관련성 있는 클래스들을 묶어 놓은 꾸러미

 

- 클래스간에 이름 충돌을 방지하기 위한 목적으로도 사용

 

- 만드는 방법

1) 클래스를 정의할때 가장 윗줄에 패키지명(경로) 지정

 package 패키지경로;
 import 구문;
 class AA{
    ..
 }

 

2) 컴파일시 패키지를 생성해준다.

형식

javac -d 생성디렉토리 클래스명.java

 

3) 패키지의 클래스를 사용할때는 import를 사용한다.

import 패키지명.클래스명;
      ..

 

 [참고]-라이브러리만들기
  c:\java\9일차>jar -cvf per.jar aa

 

import aa.bb.Person;
class  Test01_package
{
    public static void main(String[] args){
        Person per=new Person("홍길동","8012122223445");

        //System.out.println(per.toString());
        System.out.println(per);
    }
}

 

 

 

 

1. 추상클래스, 추상메소드

 

추상클래스

- 추상메소드를 포함하는 클래스

-객체를 생성할 수 없고 오로지 상속의 목적으로 만든다.

- 만드는 형식:클래스명 앞에 abstract를 붙여 만든다.

 

추상메소드

- body(몸체)를 갖지 않는 메소드

- 추상메소드는 자식클래스에서 반드시 오버라이딩해야 한다.

- 만드는 형식:메소드명앞에 abstract를 붙이고 body부분을 만들지 않는다.

 

예)

//추상클래스
abstract class MyParent
{
     //추상메소드
     public abstract void print();
        ...
}

- 만드는 이유:자식클래스에서 공통으로 구현해야 할 기능의 메소드를 가져야 하는 경우에 추상메소드를 사용한다.
 (자식에게 강제적으로 메소드를 오버라이딩하도록 제약을 줄 수 있다.)

 

ex>

//추상클래스
abstract class MyShape
{
    private String color;

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

    //추상메소드
    public abstract void draw();
}
class MyRect extends MyShape
{
    public MyRect(String color){
        super(color);
    }

    //추상메소드를 반드시 오버라이딩 해야 한다!
    public void draw(){
        System.out.println("사각형 그리기");
    }
}
class MyCircle extends MyShape
{
    public MyCircle(String color){
        super(color);
    }

    //추상메소드를 반드시 오버라이딩 해야 한다!
    public void draw(){
        System.out.println("타원 그리기");
    }
}
class Test03_abstract
{
    public static void main(String[] args)
    {
        //new MyShape();
         //==> 오류발생:객체를 생성할 수 없다.
        MyRect mr=new MyRect("빨강");

        mr.draw();

        MyShape ms=mr;    //가능!
    }
}

 

 

 

2.  인터페이스(**)

 

- 자식클래스들이 가져야 기능들의 목록을 갖음(메뉴판)

 

- 상수와 추상메소드들로만 이루어진다. (인터페이스는 빈껍데기)

 

- 만드는 형식
      interface 인터페이스명{
          상수;
          ..
          추상메소드();
          ..
      }

 

- 인터페이스는 객체를 생성할 수는 없지만 자식객체를 참조할 수는 있다.

 

- 사용이유
1) 자식클래스들이 가져야 할 기능들의 뼈대를 제공한다.

2) 클래스에서는 다중상속이 지원되지 않지만 인터페이스는 다중상속이 가능하다.

3) 인터페이스를 적절히 사용하므로써 유지보수가 수월해 진다.

 

 

ex>

//도형이 구현해야 할 기능들의 목록을 지정
interface Shape        
{      
    public static final int RED=1;

    //public static final 이 생략됨
    int BLUE=2;

    public abstract void draw();

    //public abstract 이 생략됨
    void paint();
    void resize();
}
//인터페이스를 상속받을때 implements를 사용!
class Rectangle implements Shape
{   
    public void draw(){
        System.out.println("사각형그리기");
    }

    public void paint(){
        System.out.println("사각형칠하기");
    }
    public void resize(){
        System.out.println("사각형 크기 바꾸기");
    }
}
class Test04_interface{

    public static void main(String[] args)    
    {
        //Shape sh=new Shape();
        Shape sh=new Rectangle();
        sh.draw();
        sh.paint();
        System.out.println("RED:"+Shape.RED);
    }
}

 

 

ex> 중요!! 여러번 눈에 익히자.

interface MyDbms{
    //db접속기능
    void connect();

    //db접속해제
    void disconnect();

    //sql명령어 실행
    void execute(String sql);
}
class Oracle implements MyDbms{

    public void connect(){
        System.out.println("오라클 DBMS와 연결됨!");
    }
    public void disconnect(){
        System.out.println("오라클 DBMS와 연결이 해제됨!");
    }
    public void execute(String sql){
        System.out.println("오라클 명령어를 사용해 " + sql +"을 실행함");
    }
}
class MySQL implements MyDbms{

    public void connect(){
        System.out.println("MySQL DBMS와 연결됨!");
    }
    public void disconnect(){
        System.out.println("MySQL DBMS와 연결이 해제됨!");
    }
    public void execute(String sql){
        System.out.println("MySQL 명령어를 사용해 " + sql +"을 실행함");
    }
}
class  Test05_interface{
    public static void main(String[] args)
    {
        MyDbms db=new Oracle();
        db.connect();
        db.execute("회원추가");
        db.disconnect();
    }
}

 

 

ex> //인터페이스는 다중상속이 가능하다.

interface Shape{
    void draw();
    void paint();
}
interface Point{

    void setPoint(int x,int y);
}

//인터페이스끼리는 extends를 사용한다.
interface Rect extends Shape,Point       
{
    void resize();
}
class MyRect implements Rect
{
    private int x,y;

    public void draw(){
        System.out.println(x+","+y+"의 좌표에 사각형 그리기");
    }
    public void paint(){
        System.out.println("사각형칠하기");
    }
    public void setPoint(int x,int y){
        this.x=x;
        this.y=y;
    }
    public void resize(){
        System.out.println("사각형크기 바꾸기");
    }
}
class Test06_interface
{
    public static void main(String[] args)
    {
        MyRect mr=new MyRect();
        mr.setPoint(100,200);
        mr.paint();
        mr.draw();
    }
}

 

 


3.  Object : 모든 클래스의 부모클래스

 

class Person{

    private String name;
    private int age;
   
    public Person(String name,int age)
    {
        this.name=name;
        this.age=age;
    }
    public String getName()
    {
        return name;
    }
    public int getAge()
    {
        return age;
    }
    public String toString()
    {
        String aa="name:"+name +",age:"+age;
        return aa;
    }
}
class Test07_Object
{
    public static void main(String[] args)
    {
        Object ob1=new Object();
        //Object ob2=new Object();
        Object ob2=ob1;

        if(ob1==ob2)
        {
            System.out.println("두객체는 같아요1");
        }
        if(ob1.equals(ob2))
        {
            System.out.println("두객체는 같아요2");
        }
        //public String toString()
        String aa=ob1.toString();
        System.out.println(aa);

        Person per=new Person("홍길동",10);
        //String bb=per.toString();

        //name:홍길동,age:10
        System.out.println(per);

        String cc="안녕하세요";
       
        Integer in=new Integer(100);
        //String클래스는 toString메소드를 xxx했다.
        System.out.println("cc:" + cc + ",in:"+ in);
    }
}

 

 

ex>

class Person{

    private String name;
    private int age;

    public Person(String name,int age)
    {
        this.name=name;    this.age=age;
    }
    public String getName()
    {
        return name;
    }
    public int getAge()
    {
        return age;
    }
    public boolean equals(Object obj)
    {
        Person pp=(Person)obj;

        if(name.equals(pp.name) && age==pp.age)
        {
            return true;
        }else{
            return false;
        }
    }
}
class Test08_Object{

    public static void main(String[] args)
    {
        Person per=new Person("홍길동",10);
        Person per1=new Person("홍길동",10);

        if(per.equals(per1)){
            System.out.println("두사람은 같아요!");
        }else{
            System.out.println("두사람은 달라요!");
        }

        String str=new String("안녕");
        String str1=new String("안녕");

        if(str==str1)
        {
            System.out.println("두문자열은 같아요1!");
        }
        if(str.equals(str1))
        {
            System.out.println("두문자열은 같아요2!");
        }
    }
}

 

 

 

 

 

'JAVA' 카테고리의 다른 글

lang 패키지  (0) 2014.09.12
패키지  (0) 2014.09.12
클래스간 형변환 / 다형성  (0) 2014.09.12
오버라이딩 / final의 용도  (0) 2014.09.12
상속  (0) 2014.09.12

 

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

+ Recent posts