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

 

 

1. static


1) static 메소드


- 일반멤버메소드는 객체를 생성한 후에 사용할 수 있지만   static메소드는 객체생성없이 클래스명(**)으로 호출해서 사용한다. 

- 일반멤버변수(인스턴스변수)는 사용할 수 없고 static멤버변수만 접근가능하다.

- 인스턴스변수를 사용하지 않는 독립적인 작업의 메소드를 만들때 static메소드를 사용한다.

- this는 사용할 수 없다.

- 만드는 방법 : 메소드명 앞에 static을 붙인다.


ex> static 메소드 사용예

class MyMath

{

    private int sum;

    public static int add(int x,int y)

    {

        //sum=x+y;

        //오류발생:static멤버는 일반멤버변수에는 접근 불가!!

        return x+y;    

    }

    public static int max(int x,int y)

    {    

        return (x>y)?x:y;

    }    

    public static int abs(int x)

    {

        return (x>0)?x:-x;

    }

}


class Test04_static

{

    public static void main(String[] args)

    {

        //MyMath mm=new MyMath();

        //int a=mm.add(1,2);

        //static메소드는 객체는 new로 생성후 사용하는 것이 아니라

        //객체생성없이 클래스명으로 호출한다!!!

        int sum=MyMath.add(1,2);

        System.out.println("두수합:"+sum);

        int m=MyMath.max(1,2);

        System.out.println("큰값:"+m);

 

        System.out.println("4.5의 반올림값:"+ Math.round(4.5));

    }

}

 

 



ex> 사각형의 넓이와 원의 넓이를 출력해 보세요.

class ShapeArea

{

    public static final double PI=3.141592;

    //사각형 넓이 구하는메소드

    public static double rectArea(double x,double y)

    {

        return x*y;

    }

    //정사각형 넓이

    public static double rectArea(double x)

    {

        return x*x;

    }

    //원의 넓이

    public static double circleArea(double r)

    {

        return r*r*PI;

    }

}


class Test05_static

{

    public static void main(String[] args)

    {

        System.out.println("사각형넓이:"+ShapeArea.rectArea(1.3,2.5));

        System.out.println("원의넓이:"+ShapeArea.circleArea(1.3));

        System.out.println("PI:"+ShapeArea.PI);

        System.out.println("PI:"+Math.PI);

        System.out.println("int의 최대값:"+Integer.MAX_VALUE);

    }

}

 ; 클래스명.static메소드 명으로 사용가능

; static변수,  static 메소드 가능.

; Math.PI , Integer.MAX_VALUE는

 



2) static 멤버변수


인스턴스변수(일반멤버변수)는 객체의 수만큼 생성되지만 static멤버변수는 객체의 수와 상관없이 오로지 하나만 생성되어 모든 객체가 공유해서 사용한다.

- 만드는 방법: 멤버변수앞에 static을 붙여서 만든다.

- 일반멤버변수는 객체를 new로 생성하는 순간에 만들어지지만 static멤버변수(클래스멤버변수)는 new로 생성하지 않아도 클래스가  로딩되는 순간 생성된다.

 

ex> static member변수 사용예

class MyClass

{

    private int a,b;

    private static int c;


    public MyClass()

    {

        a++;b++;c++;

    }

    public void printData()

    {

        System.out.println("a:"+a +",b:"+b+",c:"+c);

    }

}


class Test06_static

{

    public static void main(String[] args)

    {

        MyClass mc1=new MyClass();

        mc1.printData();

    

        MyClass mc2=new MyClass();

        mc2.printData();


        MyClass mc3=new MyClass();

        mc3.printData();

    }

}

 




ex> 총판매갯수를 static 변수를 사용

class Book

{

    private String title;         //도서명

    private int cnt;                //판매갯수

    private static int totCnt; //총판매갯수

    public Book(String title,int cnt)

    {

        this.title=title;

        this.cnt=cnt;

        totCnt+=cnt;

    }

    public void printInfo()

    {

        System.out.println("도서명:"+title+",판매갯수:"+cnt);

    }

    public static int getTotCnt()

    {

        return totCnt;

    }

}


class Test07_static

{

    public static void main(String[] args)

    {

        Book b1=new Book("Java",10);

        b1.printInfo();

        System.out.println("총판매갯수:"+Book.getTotCnt());

        Book b2=new Book("Jsp",5);

        b2.printInfo();

        System.out.println("총판매갯수:"+Book.getTotCnt());

    }

}

 

 



3) static초기화


ex> static초기화

class MySong

{

    private int a;

    private static String str;

 

    //static멤버를 초기화할때는 static블록을 사용한다.

   static{

        str="아리랑 아리랑 아라리요";

   }

 

    public MySong(){

        a=1000;

    }

    public void printA(){

        System.out.println("노래가격:"+a);

    }

    public static void printStr(){

        System.out.println("노랫가사:"+str);

    }

}


class  Test08_static

{

    public static void main(String[] args)

    {

        MySong.printStr();

    }

}

 

 


 

 

'JAVA' 카테고리의 다른 글

this  (0) 2014.09.12
객체배열  (0) 2014.09.12
final  (0) 2014.09.12
Overloading  (0) 2014.09.12
클래스( class )  (0) 2014.09.12

 

1. final


=> 변수를 상수화 함

=> 값을 선언과 동시에 초기화 하거나 생성자에서 초기화 할 수 있다.



ex> MyCircle객체를 생성하고 원의 넓이를 구해 보세요.

class MyCircle

{

    //반지름

    private double r;

    //원의 넓이

    private double area;

    //PI를 상수로 만듦

    private final double PI=3.141592;

    public MyCircle(double r)

    {    

        //PI=3.141592;

        // =>오류발생  (The final field MyCircle.PI cannot be assigned)

        this.r=r;

    }

    public void getArea()

    {

        area=r*r*PI;

    }

    public void print()

    {

        //PI=4.55555;

        // =>오류발생  (The final field MyCircle.PI cannot be assigned)

        System.out.println("PI:"+PI);

        System.out.println("반지름이 " + r +"인 원의 넓이:"+area);

    }

}


class  Test03_final

{

    public static void main(String[] args)

    {

        MyCircle mc=new MyCircle(10.4);

        mc.getArea();

        mc.print();

    }

}

 

 

 

변수를 초기화하지 않으면 생성자에서 초기화 해야 한다.

...

 private final double PI;

 ...

 public MyCircle(double r)

    {    

        PI=3.141592;

        // 초기화를 해야 한다. 하지 않으면  오류발생  (The blank final field PI may not have been initialized)

        this.r=r;

    }

...




'JAVA' 카테고리의 다른 글

객체배열  (0) 2014.09.12
static  (0) 2014.09.12
Overloading  (0) 2014.09.12
클래스( class )  (0) 2014.09.12
배열( array )  (0) 2014.09.12

 

1. 오버로딩 (Overloading)

 

- 같은 이름의 메소드를 중복해서 정의하는 것.

- 메소드 이름은 같지만 파라미터의 타입이나 갯수가 달라야 한다.

 

예)

class AA{

    public int add(int x,int y){

        return x+y;

    }

    //오버로딩

    public int add(int x,int y,int z){

        return x+y+z;

    }

}

 

ex> 직사각형, 정사각형의 넓이 구하기.

(MyBox객체를 생성하고 직사각형,정사각형의 넓이를 구해 보세요.)

 

class Test01_overloading{

    public static void main(String[] args){

        MyBox bb=new MyBox();
        int c=bb.getArea(10,20);   

        System.out.println("직사각형넓이:"+c);
        System.out.println("정사각형넓이:"+bb.getArea(10));
    }
}

class MyBox{
    //직사각형의 넓이 구하기
    public int getArea(int x,int y){
        return x*y;
    }

    //정사각형의 넓이 구하기
    public int getArea(int x){
        return x*x;
    }
}

 

 

 

ex> 절대값을 구하는 메소드를 갖는 MyMath라는 클래스를 만들어 보세요.

class MyMath

{

    public int abs(int x)

    {

        if(x<0){

            return -x;

        }else{

            return x;

        }

    }

    public double abs(double x)

    {

        return (x<0)?-x:x;

    }

    public float abs(float x)

    {

        return (x<0)?-x:x;

    }

    public void abs(long x)

    {

        System.out.println("절대값:"+((x<0)?-x:x));

    }

}

class Quiz01

{

    public static void main(String[] args)

    {

        MyMath mm=new MyMath();

        mm.abs(100L);

        //int a=mm.abs(10);

        System.out.println("-10의 절대값:"+ mm.abs(-10));

        System.out.println("-10.5의 절대값:"+ mm.abs(-10.5));

        System.out.println("-10.8의 절대값:"+ mm.abs(-10.8f));

    }

}

 

 

 

 

bin폴더에 생성된 class 리스트

 

 

 

 

 

 

'JAVA' 카테고리의 다른 글

static  (0) 2014.09.12
final  (0) 2014.09.12
클래스( class )  (0) 2014.09.12
배열( array )  (0) 2014.09.12
반복제어문( while문 )  (0) 2014.09.12

+ Recent posts