반응형

9.4> LoopAdder 클래스를 상속받아 다음 main() 함수와 실행 결과처럼 되도록 WhileLoopAdder, DoWhileLoopAdder 클래스를 작성하라. While , do-while 문을 이용하여 합을 구하도록 calculate() 함수를 각각 작성하면 된다.

<코드>

#include<iostream>

#include<string>

 

using namespace std;

 

class LoopAdder{  //추상 클래스

      string name;  //루프의 이름

      int x, y, sum;  //x에서 y까지의 합은 sum

      void read();  //x, y 값을 읽어 들이는 함수

      void write();  //sum 출력하는 함수

protected:

      LoopAdder(string name = ""){

            this->name = name;

      }  //루프의 이름을 받는다. 초깃값은 ""

      int getX(){ return x; }

      int getY(){ return y; }

      virtual int calculate() = 0;  //순수 가상 함수. 루프를 돌며 합을 구하는 함수

public:

      void run();  //연산을 진행하는 함수

};

 

void LoopAdder::read(){ //x, y 입력

      cout << name << ":" << endl;

      cout << "처음 수에서 두번째 수까지 더합니다. 수를 입력하세요 >>";

      cin >> x >> y;

}

 

void LoopAdder::write(){

     cout << x << "에서 " << y << "까지의 = " << sum << " 입니다" << endl;

     //결과 sum 출력

}

 

void LoopAdder::run(){

      read();  //x, y 읽는다.

      sum = calculate();  //루프를 돌면서 계산한다.

      write();  //결과 sum 출력한다.

}

 

 

 

class WhileLoopAdder : public LoopAdder{

public:

        WhileLoopAdder(string name);

protected:

        virtual int calculate();

};

WhileLoopAdder::WhileLoopAdder(string name=""):LoopAdder(name){} //생성자

int WhileLoopAdder::calculate(){

        int from=getX();

        int to=getY();

        int sum=0;

        int check=from;

        while(check<=to){sum+=check;check++;} //check to이하이면 실행

        return sum;

}

 

class DoWhileLoopAdder : public LoopAdder{

public:

        DoWhileLoopAdder(string name);

protected:

        virtual int calculate();

};

DoWhileLoopAdder::DoWhileLoopAdder(string name=""):LoopAdder(name){} //생성자

int DoWhileLoopAdder::calculate(){

        int from=getX();

        int to=getY();

        int sum=0;

        int check=from;

        do{sum+=check;check++;}while(check<=to); //무조건 처음은 실행, 그이후 check to 이하일때만 실행

        return sum;

}

 

int main(void){

        WhileLoopAdder whileLoop("While Loop");

        DoWhileLoopAdder doWhileLoop("Do while Loop");

 

        whileLoop.run();

        doWhileLoop.run();

        return 0;

}

 

 

<결과창>


반응형

'컴퓨터 & 프로그래밍 & 전자공학 > C++' 카테고리의 다른 글

추상 클래스 상속 (Int Stack)  (0) 2017.12.31
논리 게이트  (0) 2017.12.31
ForLoopAdder 클래스  (0) 2017.12.31
KmToMile class  (0) 2017.12.31
WonToDollar Class  (0) 2017.12.31
반응형

9.3> LoopAdder 클래스를 상속받아 다음 main() 함수와 실행 결과처럼 되도록 ForLoopAdder 클래스를 작성하라. ForLoopAdder 클래스의 calculate() 함수는 for 문을 이용하여 합을 구한다.

<코드>

#include<iostream>

#include<string>

 

using namespace std;

 

class LoopAdder{  //추상 클래스

      string name;  //루프의 이름

      int x, y, sum;  //x에서 y까지의 합은 sum

      void read();  //x, y 값을 읽어 들이는 함수

      void write();  //sum 출력하는 함수

protected:

      LoopAdder(string name = ""){

            this->name = name;

      }  //루프의 이름을 받는다. 초깃값은 ""

      int getX(){ return x; }

      int getY(){ return y; }

      virtual int calculate() = 0;  //순수 가상 함수. 루프를 돌며 합을 구하는 함수

public:

      void run();  //연산을 진행하는 함수

};

 

void LoopAdder::read(){ //x, y 입력

      cout << name << ":" << endl;

      cout << "처음 수에서 두번째 수까지 더합니다. 수를 입력하세요 >>";

      cin >> x >> y;

}

 

void LoopAdder::write(){//결과 sum 출력

     cout << x << "에서 " << y << "까지의 = " << sum << " 입니다" << endl;

    }

 

void LoopAdder::run(){

      read();  //x, y 읽는다.

      sum = calculate();  //루프를 돌면서 계산한다.

      write();  //결과 sum 출력한다.

}

 

class ForLoopAdder : public LoopAdder{

public:

        ForLoopAdder(string name);

protected:

        virtual int calculate();

};

ForLoopAdder::ForLoopAdder(string name=""):LoopAdder(name){} //생성자

int ForLoopAdder::calculate(){

        int from=getX();

        int to=getY();

        int sum=0;

        for(int i=from;i<to+1;i++){sum+=i;}

        return sum; //from에서 to까지 순차적으로 더한 리턴

}

int main(void){

        ForLoopAdder forLoop("For Loop: ");

        forLoop.run();

        return 0;

}

 

<결과창>


반응형

'컴퓨터 & 프로그래밍 & 전자공학 > C++' 카테고리의 다른 글

논리 게이트  (0) 2017.12.31
while, do while loop class  (0) 2017.12.31
KmToMile class  (0) 2017.12.31
WonToDollar Class  (0) 2017.12.31
Printer Class  (0) 2017.12.31
반응형

9.2> Converter 클래스를 상속받아 km mile(마일)로 변환하는 KmToMile 클래스를 작성하라. Main() 함수와 실행 결과는 다음과 같다.

<코드>

#include <iostream>

#include <string>

using namespace std;

 

class Converter {

protected:

        double ratio;

        virtual double convert(double src) = 0; //src 다른 단위로 변환한다.

        virtual string getSourceString() = 0; //src 단위 명칭

        virtual string getDestString() = 0; //dest 단위 명칭

public:

        Converter(double ratio) { this->ratio = ratio; }

        void run() {

               double src;

               cout << getSourceString() << " " << getDestString() << " 바꿉니다. ";

               cout << getSourceString() << " 입력하세요>> ";

               cin >> src;

               cout << "변환 결과 : " << convert(src) << getDestString() << endl; //src 받아서 컨버팅

        }

};

 

class KmToMile : public Converter{

protected:

        string from; //바뀌어지는 것의 이름

        string to; //바뀐 결과의 이름

public:

        KmToMile(double ratio, string from, string to);

        virtual double convert(double src);

        virtual string getSourceString();

        virtual string getDestString();

};

KmToMile::KmToMile(double ratio,string from="Km",string to="Mile"):Converter(ratio){

        this->from = from;

        this->to = to;

        this->ratio = ratio; //생성자 from,to,ratio 초기화 from to 디폴트는 "Km" "Mile"

}

double KmToMile::convert(double src){return src/ratio;}

string KmToMile::getSourceString() { return from; } //겟소스스트링 함수 오버라이딩

string KmToMile::getDestString() { return to; } //dest스트링 함수 오버라이딩

 

int main(void){

        KmToMile toMile(1.609344); //1 mile 1.609344 Km

        toMile.run();

        return 0;

}

 

<결과창>

                                   


반응형

'컴퓨터 & 프로그래밍 & 전자공학 > C++' 카테고리의 다른 글

while, do while loop class  (0) 2017.12.31
ForLoopAdder 클래스  (0) 2017.12.31
WonToDollar Class  (0) 2017.12.31
Printer Class  (0) 2017.12.31
ROM RAM class  (0) 2017.12.31
반응형

9.1> Converter 클래스를 상속받아 달러를 원화로 환산하는 WonToDollar 클래스를 작성하라. Main() 함수와 실행 결과는 다음과 같다.

<코드>

#include <iostream>

#include <string>

using namespace std;

 

class Converter {

protected:

        double ratio;

        virtual double convert(double src) = 0; //src 다른 단위로 변환한다.

        virtual string getSourceString() = 0; //src 단위 명칭

        virtual string getDestString() = 0; //dest 단위 명칭

public:

        Converter(double ratio) { this->ratio = ratio; }

        void run() {

               double src;

               cout << getSourceString() << " " << getDestString() << " 바꿉니다. ";

               cout << getSourceString() << " 입력하세요>> ";

               cin >> src;

               cout << "변환 결과 : " << convert(src) << getDestString() << endl; //src 받아서 컨버팅

        }

};

class WonToDollar : public Converter { //컨버터 클래스를 상속받은 원투달라 클래스

protected:

        string from; //바뀌어지는 것의 이름

        string to; //바뀐 결과의 이름

public:

        WonToDollar(double ratio, string from, string to);

        virtual double convert(double src);

        virtual string getSourceString();

        virtual string getDestString();

};

WonToDollar::WonToDollar(double ratio, string from = "", string to = "달러") : Converter(ratio) {

        this->from = from;

        this->to = to;

        this->ratio = ratio; //생성자 from,to,ratio 초기화 from to 디폴트는 "" "달러"

}

double WonToDollar::convert(double src) {

        return (src/ratio); //src/ratio 리턴, 컨버트 함수 오버라이딩

}

string WonToDollar::getSourceString() { return from; } //겟소스스트링 함수 오버라이딩

string WonToDollar::getDestString() { return to; } //dest스트링 함수 오버라이딩

 

int main(void) {

        WonToDollar wd(1010); //비율을 1010으로 해서 객체 생성

        wd.run(); //컨버팅 실행

        return 0;

}

 

<결과창>

                                

   


반응형

'컴퓨터 & 프로그래밍 & 전자공학 > C++' 카테고리의 다른 글

ForLoopAdder 클래스  (0) 2017.12.31
KmToMile class  (0) 2017.12.31
Printer Class  (0) 2017.12.31
ROM RAM class  (0) 2017.12.31
MyStack Class  (0) 2017.12.31
반응형

5.7> 클래스 Accumulator add() 함수를 통해 계속 값을 누적하는 클래스로서, 다음과 같이 선언된다. Accumulator 클래스를 구현하라.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
 
using namespace std;
 
class Accumulator{
private:
    int value;
public:
    Accumulator(int value);//매개 변수 value 로 멤버 value 초기화
    Accumulator& add(int n); //vlaue에 n을 더해 값 누적
    int get(); //누적된 값 value 리턴
};
Accumulator::Accumulator(int value){
    this->value=value; //value 값 이니셜라이징
}
Accumulator& Accumulator::add(int n){
    value+=n;
    return *this//리턴타입이 참조이다. this는 포인터이므로 역참조 연산자를 통해
                //참조를 리턴할 수 있다.
}
int Accumulator::get(){
    return value; //총더해진 값을 리턴
}
 
int main(void){
    Accumulator acc(10); //초기값 10
    acc.add(5).add(6).add(7); //5,6,7을 차례로 더한다
    cout<<acc.get(); //최종 더해진 값 리턴 (즉 28)
    return 0;
}
 
cs




반응형

'컴퓨터 & 프로그래밍 & 전자공학 > C++' 카테고리의 다른 글

모스 부호  (0) 2017.11.09
Book 클래스  (1) 2017.11.09
MyIntStack 클래스  (0) 2017.11.09
포인터의 증감  (0) 2017.11.09
변수와 포인터와 참조  (0) 2017.11.08
반응형

4.9> 다음은 이름과 반지름을 속성으로 가진 Circle 클래스와 이들을 배열로 관리하는 CircleManager 클래스이다. 키보드에서 원의 개수를 입력받고, 그 개수만큼 원의 이름과 반지름을 입력받고, 다음과 같이 실행되도록 main() 함수를 작성하라. Circle, CircleManager 클래스도 완성하라.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <iostream>
#include <string>
 
using namespace std;
 
class Circle{ 
private:
    int radius;
    string name;
public:
    void setCircle(string name, int radius){ //멤버 name과 radius를 set해줌.
        this->name=name; this->radius=radius;
    }
    double getArea(){return radius*radius*3.14;} //원의 면적 리턴
    string getName(){return name;} //원의 이름 리턴
};
 
class CircleManager{
private:
    Circle *p; //Circle형 포인터 p
    int size;
public:
 
    CircleManager(int size){ //컨스트럭터
        this->size=size
        p=new Circle[size]; //size크기만큼의 Circle형 동적 객체 배열 생성
        int radius; string name;
        for(int i=0;i<size;i++){
            cin.ignore(100,'\n'); //cin은 개행문자를 버퍼에 남겨놓기 때문에 버퍼에서 비워줘야 한다.
                                //그렇지 않으면 다음 루프의 getline이 개행문자 + 입력한 문자열을 받아버린다.
            cout<<"원 "<<i+1<<"의 이름과 반지름 >>";
            getline(cin,name,' '); // space를 delimeter로 설정하여 이름을 받는다.
            cin>>radius;     //radius는 cin으로 받는다.
            p[i].setCircle(name,radius); //Circle을 set 해줌.
        }
    cin.ignore(); //마지막 개행문자 버퍼에서 제거
    }
    ~CircleManager(){delete []p;} //동적 Circle 객체 배열 해당 메모리 힙으로 반환
    void searchByName(){
        string cmp;
        cout<<"검색하고자 하는 원의 이름>> ";
        getline(cin,cmp,'\n'); //cmp를 getline으로 개행문자 나올때까지 받는다.
        for(int i=0;i<(this->size);i++){
            if(cmp==(p[i].getName()))  //cmp와 i번째 동적circle의 name이 같으면
            {cout<<"도넛의 면적은 "<<p[i].getArea()<<endl//i번째 동적circle의 area 반환
            break;}
        }
    }
    void searchByArea(){
        int area;
        cout<<"최소 면적을 정수로 입력하세요>> ";
        cin>>area; //area를 받는다.
        cout<<area<<"보다 큰 원을 검색합니다."<<endl;
        for(int i=0;i<(this->size);i++){ //동적 객체 배열 전부 순회하여 area보다 
            if(p[i].getArea()>area) //p번째 circle 객체의 넓이가 크면 출력
                cout<<p[i].getName()<<"의 면적은 "<<p[i].getArea()<<", ";
        }
        cout<<endl//개행 출력
    }
};
 
int main(void){
    int size;
    cout<<"원의 개수 >> " ; 
    cin>>size//원의 개수 정함
    CircleManager m(size); //CircleManager객체 생성
    m.searchByName(); //Name으로 찾기
    m.searchByArea(); //특정 Area 초과인것 찾기
    
    return 0;
}
 
cs




반응형

'컴퓨터 & 프로그래밍 & 전자공학 > C++' 카테고리의 다른 글

float와 double  (0) 2017.11.05
히스토그램  (0) 2017.11.03
Person, Family 클래스  (0) 2017.11.03
원의 개수와 반지름  (0) 2017.11.03
문자열 문자 랜덤 수정  (0) 2017.11.03
반응형

4.8> 다음에서 Person은 사람을, Family는 가족을 추상화한 클래스로서 완성되지 않은 클래스이다. 다음 main()이 작동하도록 Person Family 클래스에 필요한 멤버들을 추가하고 코드를 완성하라.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <string>
 
using namespace std;
 
class Person{ //Person 클래스
private:
    string name; 
public:
    Person(string name){this->name=name;} //객체멤버 name을 매개변수 name으로 초기화
    Person(){} //디폴트 생성자
    string getName(){return name;} // 멤버변수 name 리턴
    void setName(string name){this->name=name;} //멤버변수 name set함수
    
};
 
class Family{ //Family 클래스
private:
    Person *p; //Person형 포인터 p
    int size//int형 변수 size
    string Fname; //string 형 객체 Fname
public:
    Family(string name, int size){
        p=new Person[size]; //size 크기만큼 동적 Person 객체 배열 생성
        setFname(name); //Fname을 name으로 초기화
        this->size=size//멤버변수 size를 매개변수 size로 초기화
    }
    string getFname(){return Fname;} //Fname 리턴
    int getSize(){return size;} //size 리턴
    void setFname(string Fname){this->Fname=Fname;} //멤버변수 Fname을 매개변수 Fname으로 셋
    void setName(int num, string name){ 
        p[num].setName(name); //num에 해당하는 인덱스에 존재하는 동적 person 객체 배열 원소의 name 셋
    }
    void show(){
        cout<<getFname()<<"가족은 다음과 같이 "<<getSize()<<"명 입니다."<<endl//size 리턴받아 출력
        for(int i=0;i<size;i++){  //i가 0에서부터 size보다 작을때까지
            cout<<p[i].getName()<<"\t"//동적 person 객체 배열 원소에서 getName멤버 함수 호출하여 출력후 탭문자 출력
        }
        cout<<endl// 한줄 내리기
    }
    ~Family(){delete []p;} //소멸자는 동적person배열에 할당된 메모리를 힙에 반납한다. 
};
 
int main(void){
    Family *simpson = new Family("Simpson"3);  //Fname "Simpson", size 3으로 초기화된 Family형 동적 객체, 그걸 가리키는 포인터 simpson
    simpson->setName(0"Mr. Simpson"); //simpson이가리키는 객체 안에서원소3개의 person형 동적 객체 배열이 생성되었고 그중 0번 원소 초기화
    simpson->setName(1"Mrs. Simpson"); //1번 원소 초기화
    simpson->setName(2"Bart Simpson"); //2번 원소 초기화
    simpson->show(); //출력 함수
    delete simpson; //동적 메모리 힙으로 반환
}
 
cs



반응형

'컴퓨터 & 프로그래밍 & 전자공학 > C++' 카테고리의 다른 글

히스토그램  (0) 2017.11.03
Circle, CircleManager 클래스  (0) 2017.11.03
원의 개수와 반지름  (0) 2017.11.03
문자열 문자 랜덤 수정  (0) 2017.11.03
변수와 포인터와 레퍼런스  (0) 2017.10.27
반응형

7.8>다음은 String만 다루는 MyClass 코드이다. MyClass를 제네릭 클래스 MyClass<E>로 일반화하고, 이를 이용하는 main() 메소드를 만들어 프로그램을 완성하라.


public class MyClass {

      private String s;

      public MyClass(String s) {

            this.s = s;

      }

      void setS(String s) {

            this.s = s;

      }

      String getS() {

            return s;

      }

}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package SecondHW;
class MyClass<E> {  //제네릭 클래스 MyClass 타입 매개 변수는 E, 설정하는 것에 따라 자유자재로 바뀜
    private E e; //private 형이라서 Myclass내 접근이 아니면 변경 불가한 E형 변수 e
    public MyClass(E e) { //생성자 ,매개변수를 객체 e 에 대입
        this.e = e;
    }
    void setS(E e) { //e를 정해주는 setS메소드 매개변수 e를 객체의 e에 대입 디폴트형
        this.e = e;
    }
    E getS() {  //객체의 e를 반환해주는 getS메소드 디폴트형
        return e;
    } //제네릭은 클래스와 인터페이스에만 적용되므로 자바 기본 타입은 사용 불가능
}
public class GenericPractice {
    public static void main(String[] args) {
        MyClass<Integer> i = new MyClass<Integer>(1); //정수형 MyClass i 래퍼 클래스 사용 
        MyClass<Double> d = new MyClass<Double>(2.7); //실수형 MyClass d 래퍼 클래스 사용
        MyClass<String> s = new MyClass<String>("For the Horde"); //문자열형 Myclass s
        System.out.println(i.getS()); //getS함수를 통해 리턴된 값 출력
        System.out.println(d.getS());
        System.out.println(s.getS());
        i.setS(3); //i의 e를 3으로 set
        d.setS(3.14); //d의 e를 3.14으로 set
        s.setS("탕수육소스다");//s의 e를 "탕수육소스다"로 set
        System.out.println(i.getS());
        System.out.println(d.getS());
        System.out.println(s.getS()); //출력
    }}
 
cs




반응형

'컴퓨터 & 프로그래밍 & 전자공학 > JAVA' 카테고리의 다른 글

학생 정보  (0) 2017.06.19
학점 계산  (0) 2017.06.19
가장 큰 수  (0) 2017.06.19
겜블링 게임  (0) 2017.06.19
가위바위보  (0) 2017.06.19
반응형

6.4> int 타입의 x, y, radius 필드를 가지는 Circle 클래스를 작성하라. Equals() 메소드를 재정의하여 두 개의 Circle 객체의 반지름이 같으면 두 Circle 객체가 동일한 것으로 판별하도록 하라. Circle 클래스의 생성자는 3개의 인자를 가지며 x, y, radius 필드를 인자로 받아 초기화한다


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package SecondHW;
class Circle{ //default 접근의 Circle 클래스
    int x; //int 형 변수 x
    int y;//int 형 변수 y
    int radius;//int 형 변수 radius
    public Circle(int x,int y,int radius){ //Circle 클래스의 생성자
        this.x=x; //객체 의 x에 인자 x 대입
        this.y=y; //객체 의 y에 인자 y 대입
        this.radius=radius; //객체 의 radius에 인자 radius 대입
    }
     public boolean equals(Circle c2){ //java.lang 패키지에 속한 Object 클래스(자바클래스구조의 최상위)의 equals 메소드 오버라이딩
        if(this.radius==c2.radius) //객체의 radius와 인자 c2의 radius 비교
            return true//맞으면 true 반환
        else
            return false//다르면 false 반환}}
public class CircleDicision {
 
    public static void main(String[] args) {
        Circle cir1 = new Circle(1,2,3); //cir1 의 x=1,y=2,radius=3으로 초기화
        Circle cir2 = new Circle(2,4,3); //cir2 의 x=2,y=4,radius=3으로 초기화
        System.out.printf("cir1의  x :  %d y : %d  rad : %d \n",cir1.x,cir1.y,cir1.radius); //객체의 인트형 변수들 출력
        System.out.printf("cir2의  x :  %d y : %d  rad : %d \n",cir2.x,cir2.y,cir2.radius); //객체의 인트형 변수들 출력
        if(cir1.equals(cir2)) //cir1.equals(cir2)가 참이면
            System.out.println("같은 원입니다."); //같은 원 출력
        else //아니면
            System.out.println("다른 원입니다."); //다른 원 출력
    }
}
 
cs




반응형

'컴퓨터 & 프로그래밍 & 전자공학 > JAVA' 카테고리의 다른 글

가위바위보  (0) 2017.06.19
대문자 개수 세기  (0) 2017.06.19
추상 클래스  (0) 2017.06.18
상속 클래스  (0) 2017.06.18
ArrayUtility class  (0) 2017.06.18
반응형

5.5>추상 클래스의 서브 클래스 만들기에 필요한 추상 메소드 오버라이딩과 super()의 사용에 관한 문제이다. 다음과 같은 MyPoint 추상 클래스가 있다.




MyPoint를 상속받는 MyColorPoint 클래스를 작성하라. MyColorPoint의 생성자는 MyColorPoint(int x, int y, String color)로 하라. 그리고 다음과 같은 main() 메소드를 삽입하여 실행되도록 하라.





1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package HW1_JAVA;
abstract class MyPoint{ // 추상 클래스 MyPoint
    int x; int y;  //int형 변수 x,y 선언
    public MyPoint(int x,int y){  //생성자 MyPoint int형 변수인 인자 x,y
        this.x=x; this.y=y; //객체의 x에 인자 x 대입, 객체의 y에 인자 y 대입
    }
    protected abstract void move(int x,int y); //추상 메소드 move,int형 인자 x,y
    protected abstract void reverse(); //추상 메소드 reverse
    protected void show(){ // 객체의 x와 y를 출력하는 메소드 show
        System.out.println(x+","+y);
    }
}
class MyColorPoint extends MyPoint{  //MyPoint를 상속하는 MyColorPoint 클래스
    String s; //스트링형 오브젝트 s
    public MyColorPoint(int x, int y, String Color){ //생성자 인자는 int형 x,y와 string Color
        super(x,y); //슈퍼클래스의 생성자 호출
        this.s=Color; //String 레퍼런스 변수 Color가 가리키는 문자열을 this.s가 가리키게함
    }
    protected void move(int x,int y){ //상속받은 추상 메소드 오버라이딩
        this.x=x; this.y=y; //객체의 x에 인자 x 대입, 객체의 y에 인자 y 대입
    }
    protected void reverse(){ //상속받은 추상 메소드 오버라이딩
        int temp; // int형 변수 temp, 빈 물컵 역할
        temp=this.x;  //x와 y를 스왑하는 과정
        this.x=this.y;
        this.y=temp;
    }
    protected void show(){ //슈퍼클래스의 메소드 show 오버라이딩
        System.out.println(x+","+y+","+s);  //x와 y와 s를 출력하는 메소드 show
    }
}
public class Abstract {
    public static void main(String[] args) {//MyPoint형 객체를 가리키는 레퍼런스 변수 p
        MyPoint p=new MyColorPoint(2,3,"blue"); //MyColorPoint클래스의 객체 생성, 업캐스팅
        p.move(34); // 동적 바인딩에 의해 MyColorPoint에서 오버라이딩한 메소드move가 호출됨
        p.reverse(); //동적 바인딩에 의해 MyColorPoint에서 오버라이딩한 메소드reverse가 호출됨
        p.show(); //동적 바인딩에 의해 MyColorPoint에서 오버라이딩한 메소드 show가 호출됨
    }
}
 
cs


반응형

'컴퓨터 & 프로그래밍 & 전자공학 > JAVA' 카테고리의 다른 글

대문자 개수 세기  (0) 2017.06.19
메소드 오버라이딩  (0) 2017.06.18
상속 클래스  (0) 2017.06.18
ArrayUtility class  (0) 2017.06.18
직사각형 클래스  (0) 2017.06.18
반응형

5.4> main() 함수를 다음과 같이 수행할 수 있도록 하기 위한 CPoint 클래스와 CColorPoint 클래스를 작성하고 전체 프로그램을 완성하라. CColorPoint 클래스의 어떤 메소드에서도 System.out.println()을 호출해서는 안 된다. CPoint 클래스는 생성자가 오직 하나뿐이다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package HW1_JAVA;
class CPoint{ //class CPoint 선언
    int a; int b; String s;  //int형 변수 a,b 와 String s 선언
    protected CPoint(int a, int b){ //int a와 int b를 argument 로 갖는 생성자
        this.a=a; this.b=b; this.s=""//this.a에 a대입 this.b에 b 대입 s에 "" 대입(색깔들어갈자리)
    }
    void show(){
        System.out.println("("+a+","+b+")"+s); // a와 b와 s를 출력하는 메소드 show
    } //toString 메소드는 Object 클래스에 속한다. 
    public String toString(){ //메소드 오버라이딩 시 슈퍼 클래스 메소드의 접근지정자보다 접근 범위가 좁아질 수 없다.
        return "("+a+","+b+")"+" 입니다";
    } //toString : println의 인자로 객체의 레퍼런스 변수가 전달되면 해당 인스턴스의 toString 메소드가 호출되면서
    } // 리턴값으로 반환되는 문자열이 나온다.
class CColorPoint extends CPoint{ //CPoint를 상속하는 클래스 CColorPoint
        CColorPoint(int a, int b,String s)
        {
            super(a,b); //CColorPoint의 슈퍼클래스인 CPoint의 생성자 호출
            this.s=s; // this.s에 인자 s 대입
        }
    }
public class PointCl {
    public static void main(String[] args) {
        CPoint a,b; //CPoint 형 클래스를 가리키는 레퍼런스 변수 a,b
        a=new CPoint(2,3); // CPoint 클래스의 객체 생성(인자는 2,3) 레퍼런스 변수는 a
        b=new CColorPoint(3,4,"red"); //업캐스팅된 CColorPoint 클래스의 객체를 가리키는 레퍼런스변수 b
        a.show(); //a.show 메소드 호출
        b.show(); //b.show 메소드 호출
        System.out.println(a); //a 출력인데 a.toString의 리턴값이 출력됨
        System.out.println(b); //b 출력인데 b.toString의 리턴값이 출력됨
    }
}
 
cs




반응형

'컴퓨터 & 프로그래밍 & 전자공학 > JAVA' 카테고리의 다른 글

메소드 오버라이딩  (0) 2017.06.18
추상 클래스  (0) 2017.06.18
ArrayUtility class  (0) 2017.06.18
직사각형 클래스  (0) 2017.06.18
돈 단위 나누기  (0) 2017.06.18
반응형

4.2>. 다음과 같은 멤버를 가지는 직사각형을 표현하는 Rectangle 클래스를 작성하라.

- int 타입의 x1, y1, x2, y2 필드 : 사각형을 구성하는 두 점의 좌표

- 생성자 2: 매개 변수 없는 생성자와 x1, y1, x2, y2의 값을 설정하는 생성자

- void set(int x1, int y1, iny x2, int y2) : x1, y1, x2, y2좌표 설정

- int square() : 사각형 넓이 리턴

- void show() :좌표와 넓이 등 직사각형 정보의 화면 출력

) 사각형의 좌표는 (0,0), (0,0)입니다.

- boolean equals(Rectangle r) : 인자로 전달된 객체 r과 현 객체가 동일한 직사각형이면 true 리턴

 

Rectangle을 이용한 main() 메소드는 다음과 같으며 이 main() 메소드가 잘 작동하도록 하라.

public class RectManager {

             public static void main(String args[]) {

                           Rectangle r = new Rectangle();

                           Rectangle s = new Rectangle(1,1,2,3);

                           r.show();

                           s.show();

                           System.out.println(s.square());

                           r.set(-2,2,-1,4);

                           r.show();

                           System.out.println(r.square());

                          if(r.equals(s))

                                        System.out.println(" 사각형은 같습니다.");

             }

}



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package HW1_JAVA;
class Rectang{ //Rectang class 선언
        int x1,y1,x2,y2; //int 형 변수 x1,y1,x2,y2 선언
        Rectang(){  //constructor Rectang 아규먼트 없을때
            this.x1=0;  // 객체의 x1,y1,x2,y2에 0 대입
            this.y1=0;
            this.x2=0;
            this.y2=0;}
        Rectang(int x1, int y1, int x2, int y2){
            this.x1=x1;  //객체의 x1,y1,x2,y2에 인자 x1,y1,x2,y2 대입
            this.y1=y1;     //하는 constructor (오버로딩)
            this.x2=x2;
            this.y2=y2;}
        void set(int x1, int y1, int x2, int y2){
            this.x1=x1; //객체의 x1,y1,x2,y2에 인자 x1,y1,x2,y2 대입하는 메소드 set
            this.y1=y1;
            this.x2=x2;
            this.y2=y2;}
        int square(){ //메소드 square 선언
            int length=Math.abs(this.x2-this.x1); //밑변은 x2-x1한 것의 절대값
            int height=Math.abs(this.y2-this.y1); //높이는 y2-y1한 것의 절대값
            return length*height;} //밑변*높이 반환
        void show(){ //메소드 show 선언, 좌표와 밑변 넓이를 화면에 출력해준다. printf를 사용하였다.
            System.out.printf("사각형의 좌표는 (%d,%d),(%d,%d) 입니다.\n",this.x1,this.y1,this.x2,this.y2);
            System.out.printf("사각형의 밑변은 %d, 높이는 %d입니다.\n",Math.abs(this.x2-this.x1),Math.abs(this.y2-this.y1));;
            System.out.printf("사각형의 넓이는 %d입니다.\n",square());}
        boolean equals(Rectang r){ //리턴값 true와 false만 있는 메소드 equals
        if((Math.abs(this.x2-this.x1)==Math.abs(r.x2-r.x1))&&(Math.abs(this.y2-this.y1)==Math.abs(r.y2-r.y1)))
            return true//밑변길이와 높이를 비교해서 둘다 같으면 true 반환
        else //아니면 false 반환
            return false;}}
public class Square {
    public static void main(String[] args) {
        Rectang r = new Rectang();  //인자없는 생성자로 생성한 Rectang의 객체와 레퍼런스 변수 r
        Rectang s = new Rectang(1,1,2,3); //인자를 넣어준 Rectang의 객체와 레퍼런스 변수 s
        r.show(); //r이 가리키는 객체의 show 메소드 호출
        s.show(); //s가 가리키는 객채의 show 메소드 호출
        System.out.println(s.square()); //s가 가리키는 객체의 square 메소드 호출 후 리턴 값 출력
        r.set(-2,2,-1,4); //r이 가리키는 객체의 set 메소드 호출 
        r.show(); //r이 가리키는 객체의 show 메소드 호출
        System.out.println(r.square()); //r이 가리키는 객체의 square 메소드 호출 후 리턴 값 출력
        if(r.equals(s)) //만약 r.equals(s)가 ture를 반환하면(r과 s 비교)
            System.out.println("두 사각형은 같습니다.");  // 해당 스트링 출력
    }}
 
cs




반응형

'컴퓨터 & 프로그래밍 & 전자공학 > JAVA' 카테고리의 다른 글

상속 클래스  (0) 2017.06.18
ArrayUtility class  (0) 2017.06.18
돈 단위 나누기  (0) 2017.06.18
2차원 배열  (0) 2017.06.18
정수 오름차순 정렬기  (0) 2017.06.18

+ Recent posts