public String breed; public String color; // 메소드정의 public void bark()... public void bite()... public void eat()... // 종 // 색깔 p 기초변수는 int, flo

Similar documents
(8) getpi() 함수는정적함수이므로 main() 에서호출할수있다. (9) class Circle private double radius; static final double PI= ; // PI 이름으로 로초기화된정적상수 public

gnu-lee-oop-kor-lec06-3-chap7

PowerPoint Presentation

PowerPoint Presentation

PowerPoint Presentation

Microsoft PowerPoint - Lect04.pptx

PowerPoint Presentation

JAVA PROGRAMMING 실습 08.다형성

PowerPoint Presentation

<4D F736F F F696E74202D20C1A63233C0E520B1D7B7A1C7C820C7C1B7CEB1D7B7A1B9D628B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

<4D F736F F F696E74202D20C1A63139C0E520B9E8C4A120B0FCB8AEC0DA28B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

<4D F736F F F696E74202D20C1A63038C0E520C5ACB7A1BDBABFCD20B0B4C3BC4928B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

쉽게 풀어쓴 C 프로그래밍

PowerPoint Presentation

쉽게 풀어쓴 C 프로그래밍

5장.key

gnu-lee-oop-kor-lec10-1-chap10

JAVA 프로그래밍실습 실습 1) 실습목표 - 메소드개념이해하기 - 매개변수이해하기 - 새메소드만들기 - Math 클래스의기존메소드이용하기 ( ) 문제 - 직사각형모양의땅이있다. 이땅의둘레, 면적과대각

PowerPoint Presentation

PowerPoint Presentation

PowerPoint Presentation

Microsoft PowerPoint - 2강

<4D F736F F F696E74202D20C1A63138C0E520C0CCBAA5C6AE20C3B3B8AE28B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

쉽게 풀어쓴 C 프로그래밍

Microsoft PowerPoint - 14주차 강의자료

PowerPoint Presentation

Microsoft PowerPoint - 04-UDP Programming.ppt

제8장 자바 GUI 프로그래밍 II

<4D F736F F F696E74202D20C1A63230C0E520BDBAC0AE20C4C4C6F7B3CDC6AE203128B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

Java Programing Environment

PowerPoint Presentation

쉽게 풀어쓴 C 프로그래밍

PowerPoint Presentation

PowerPoint 프레젠테이션

9장.key

Microsoft Word - java18-1-final-answer.doc

자바GUI실전프로그래밍2_장대원.PDF

01-OOPConcepts(2).PDF

q 이장에서다룰내용 1 객체지향프로그래밍의이해 2 객체지향언어 : 자바 2

쉽게 풀어쓴 C 프로그래밍

<4D F736F F F696E74202D20C1A63236C0E520BED6C7C3B8B428B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

ch09

JAVA PROGRAMMING 실습 05. 객체의 활용

Microsoft PowerPoint - Java7.pptx

Microsoft PowerPoint - ÀÚ¹Ù08Àå-1.ppt

제11장 프로세스와 쓰레드

Microsoft PowerPoint - java1-lecture6.ppt [호환 모드]

Design Issues

PowerPoint Presentation

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션

쉽게 풀어쓴 C 프로그래밍

PowerPoint Presentation

No Slide Title

쉽게 풀어쓴 C 프로그래밊

쉽게 풀어쓴 C 프로그래밍

슬라이드 1

JAVA PROGRAMMING 실습 09. 예외처리

PowerPoint 프레젠테이션

05-class.key

PowerPoint Presentation

쉽게

11장.key

09-interface.key

강의자료

Microsoft PowerPoint 자바-기본문법(Ch2).pptx

No Slide Title

TEST BANK & SOLUTION

PowerPoint Presentation

JAVA PROGRAMMING 실습 02. 표준 입출력

Microsoft PowerPoint 장강의노트.ppt

예제 2) Test.java class A intvar= 10; void method() class B extends A intvar= 20; 1"); void method() 2"); void method1() public class Test 3"); args) A

PowerPoint 프레젠테이션

JAVA PROGRAMMING 실습 07. 상속

(Microsoft PowerPoint - java1-lecture11.ppt [\310\243\310\257 \270\360\265\345])

Microsoft Word - java19-1-final-answer.doc

10.0pt1height.7depth.3width±â10.0pt1height.7depth.3widthÃÊ10.0pt1height.7depth.3widthÅë10.0pt1height.7depth.3width°è10.0pt1height.7depth.3widthÇÁ10.0pt1height.7depth.3width·Î10.0pt1height.7depth.3width±×10.0pt1height.7depth.3width·¡10.0pt1height.7depth.3width¹Ö pt1height.7depth.3widthŬ10.0pt1height.7depth.3width·¡10.0pt1height.7depth.3width½º, 10.0pt1height.7depth.3width°´10.0pt1height.7depth.3widthü, 10.0pt1height.7depth.3widthº¯10.0pt1height.7depth.3width¼ö, 10.0pt1height.7depth.3width¸Þ10.0pt1height.7depth.3width¼Ò10.0pt1height.7depth.3widthµå

PowerPoint 프레젠테이션

Microsoft PowerPoint - java1-lab5-ImageProcessorTestOOP.pptx

<322EBCF8C8AF28BFACBDC0B9AEC1A6292E687770>

PowerPoint Presentation

(Microsoft PowerPoint - java2-lecture3.ppt [\310\243\310\257 \270\360\265\345])

PowerPoint 프레젠테이션

JAVA PROGRAMMING 실습 05. 객체의 활용

No Slide Title

PowerPoint Template

PowerPoint Presentation

PowerPoint 프레젠테이션

Modern Javascript

8장.그래픽 프로그래밍

10장.key

쉽게 풀어쓴 C 프로그래밍

No Slide Title

Spring Data JPA Many To Many 양방향 관계 예제

설계란 무엇인가?

PowerPoint Presentation

public class FlowLayoutPractice extends JFrame { public FlowLayoutPractice() { super("flowlayout Practice"); this. Container contentpane = getcontentp

PowerPoint Template

자바 프로그래밍

JAVA PROGRAMMING 실습 02. 표준 입출력

Transcription:

p.142 1. 객체 2. 1960, SIMULA p.146 1. 데이터, 알고리즘 2. 데이터 3. 클래스를변경하기가쉬워진다. p.148 1. 메시지 2. start(), stop(), speedup(int s), speeddown(int s), turnleft(int degree), turnright(int degree) p.157 1. 클래스 2. 변수는공유되지않는다. 즉변수는각객체마다하나씩생성된다. 하지만메소드는공유된다. 3. 필드, 메소드 4. 도트 (.) 5. 필드 6. class Stock() // 필드정의 public int num; // 상품번호 public int count; // 메소드정의 public void stockup() count++; public void stockdown() count--; 7. class Dog() // 필드정의 public String name; // 재고수량 // 이름

public String breed; public String color; // 메소드정의 public void bark()... public void bite()... public void eat()... // 종 // 색깔 p.161 1. 기초변수는 int, float, char 등의기초자료형을가지는변수이고, 참조변수는객체를참조할때사용되는변수이다. 2. 두개의참조변수가하나의객체를가리킨다. 3. 참조변수에 null 을대입한다. 예를들면 p = null; 와같다. p.168 1. 기초형, 참조형 2. new 3. String 4. length() 5. + class BankAccount // 은행계좌 int balance; // 잔액을표시하는변수 void deposit(int amount) // 저금 balance += amount; void withdraw(int amount) // 인출 balance -= amount; int getbalance() // 잔고반환 return balance; public class BankAccountTest public static void main(string[] args) BankAccount b = new BankAccount();

(1) BankAccount b = new BankAccount(); b.balance = 100; b.withdraw(60); System.out.println(b.getBalance()); (2) void addinterest() balance = balance + balance*0.075; (3) void withdraw(int amount) // 인출 if( amount < 0 ) return; balance -= amount; (4) 하나의소스파일안에는한개의 public 클래스만이있어야한다. 원칙적으로 public 클래스들은별도의소스파일안에정의하여야한다. 1. class NumberBox public int ivalue; public float fvalue; public class NumberBoxTest public static void main(string[] args) NumberBox b = new NumberBox(); b.ivalue=10; b.fvalue=(float)1.2345; System.out.println(b.ivalue); System.out.println(b.fvalue); 2. 상태 ( 속성 ) 변수 int year int month int day 설명년도월일

동작 ( 행동 ) 메소드이름 void setdate(int y, int m, int d) void printdate() 3. 객체가생성되지않았다. new 를이용하여서객체를생성해준다. class Rectangle int width, height; int area() return width*height; public class Test public static void main(string[] args) Rectangle myrect; myrect = new Rectangle(); myrect.width = 10; myrect.height = 20; System.out.println(" 면적은 " + myrect.area()); 4. (a) 생각이현실이된다 (b) 문자열의길이는 7 (c) ABCDEFG (d) 2 + 3 = 5 (e) 2 + 3 = 23 설명날짜를설정날짜를출력 1. class Rectangle int w; int h; int area() return w*h; int perimeter() return 2*(w+h); public class RectangleTest public static void main(string[] args) Rectangle myrect; myrect = new Rectangle(); myrect.w = 10; myrect.h = 20; System.out.println(" 면적은 " + myrect.area());

2. class Date int year; int month; int day; void print1() System.out.println(year + "." + month + "." + day); public class DateTest public static void main(string[] args) Date d; d = new Date(); d.year = 2012; d.month = 9; d.day = 5; d.print1(); 3. class ComplexNumber int real; int imag; void print() System.out.println(real + "+ i" + imag); public class ComplexNumberTest public static void main(string[] args) ComplexNumber c; c = new ComplexNumber(); c.real = 10; c.imag = 20; c.print(); 4. class Movie int year; String title; void print()

System.out.println(year + ": " + title); public class MovieTest public static void main(string[] args) Movie m; m = new Movie(); m.year = 2012; m.title = "Total Recall"; m.print(); 5. import java.util.scanner; public class StringTest public static void main(string[] args) String s; Scanner sc = new Scanner(System.in); System.out.println(" 문자열을입력하시오 : "); s = sc.next(); for(int i=0;i<s.length();i++) System.out.print(s.charAt(s.length()-1-i)); 6. import java.util.*; public class ConVo public static void main(string[] args) String s; char s2; int count1 = 0, count2 = 0; Scanner scan = new Scanner(System.in); System.out.print(" 문자열을입력하세요 : "); s = scan.next(); for(int i = 0; i < s.length(); i++) s2 = s.charat(i); if((s2 >= 'A' && s2 <= 'Z') (s2 >= 'a' && s2 <= 'z')) if(s2=='a' s2=='e' s2 == 'i' s2 == 'o' s2 == 'u') count1++; else count2++; System.out.println(" 자음의개수 : " + count2); System.out.println(" 모음의개수 : " + count1); 7.

import java.util.*; public class Password public static void main(string[] args) String s; String id="abcdef"; Scanner scan = new Scanner(System.in); System.out.print(" 아이디를입력하세요 : "); s = scan.next(); if( s.equalsignorecase(id) ) System.out.println(" 로그인이성공하였습니다 "); else System.out.println(" 로그인이실패하였습니다 "); p.179 1. 크게나누면기초형변수와참조형변수가존재한다. 2. 잘못된값이저장되는것은사전에체크할수있고또필요할때마다값을다시계산하여서반환할수도있다. 3. 필드는클래스안에선언되는변수이다. 지역변수는메소드안에선언되어서메소드안에서만사용되는변수이다. p.185 1. 중복메소드 (overloading method) 2. 값을반환하지않는메소드를나타낸다. 3. public void printmyname() String name; System.out.println(" 이름을입력하시오 :"); Scanner scan = new Scanner(System.in); name = scan.nextline(); System.out.println(name); p.187

1. TV -ison : bool -channel: int +turnon() +turnoff() +setchannel(int) +getchannel(); int 1. (1) class Box // 필드정의 int width; int length; int height; // 메소드정의 (2) class Box public int getwidth() return width; public void setwidth(int width) this.width = width; public int getlength() return length; public void setlength(int length) this.length = length; public int getheight() return height; public void setheight(int height) this.height = height; // 필드정의 int width; int length; int height; // 메소드정의 (3) public int getvolume()

(4) return width*length*height; public void print() System.out.println(" 가로 :" + width); System.out.println(" 세로 :" + width); System.out.println(" 높이 :" + width); (5) public class BoxTest public static void main(string[] args) (6) (7) (8) 1000000 Box box1; box1 = new Box(); box1.setwidth(100); box1.setlength(100); box1.setheight(100); System.out.println(box1.getVolume()); (9) (10) 1000000 가로 :200 세로 :200 높이 :200 Box box2; box2 = new Box(); box2.setwidth(200); box2.setlength(200); box2.setheight(200); box1 = box2; box1.print(); 1. 설정자에서매개변수를통하여잘못된값이넘어오는경우, 이를사전에차단할수있다. 필요할때마다필드값을계산하여반환할수있다. 접근자만을제공하면자동적으로읽기만가능한필드를만들수있다. 2. class Television

private String model; void setmodel(string b) // 설정자 model = b; String getmodel() // void->string return model; public class TelevisionTest public static void main(string[] args) Television t = new Television(); // () 을붙여주어야함! t.setmodel("stv-101"); String b = t.getmodel(); // 객체참조변수 t 를적어주어야함. 3. (1) public String gettitle() return title; public void settitle(string title) this.title = title; public String getdirector() return director; public void setdirector(string director) this.director = director; public String getactors() return actors; public void setactors(string actors) this.actors = actors;

(2) Movie -title : String -director : String -actor : String +gettitle() +getdirector() +getactor() +settitle() +setdirector() +setacotr() (3) public class Movie private String title, director, actors; public String gettitle() return title; public void settitle(string title) this.title = title; public String getdirector() return director; public void setdirector(string director) this.director = director; public String getactors() return actors; public void setactors(string actors) this.actors = actors; (4) Movie m = new Movie(); m.settitle("transformer"); 4. (1) 은행, 정기예금계좌, 보통예금계좌, 고객 (2) SavingsAccount, CheckingAccount, Customer (3) Account: 계좌번호, 소유자이름, 잔액, deposit(), withdraw() SavingsAccount extends Account: 이자율, 이자계산 () CheckingAccount extends Account: 카드번호 ( 수표번호 ), 부도여부 Customer: 이름, 주소, 소유한계좌번호

class Account String AccNumber; String ownername; int balance; void deposit(int amount) balance += amount; void withdraw(int amount) if (balance > amount) balance -= amount; class CheckingAccount extends Account String cardnumber; boolean status; 1. Circle -r : double -cx : double -cy : double +area() +setr() +setcx() +setcy() +getr() +getcx() +getcy() class Circle double r; double cx; double cy; public double area() return 3.141592*r*r; public double getr() return r; public void setr(double r) this.r = r;

public double getcx() return cx; public void setcx(double cx) this.cx = cx; public double getcy() return cy; public void setcy(double cy) this.cy = cy; public class CircleTest public static void main(string[] args) Circle c = new Circle(); c.setr(10.0); System.out.println(c.area()); 2. class Book private String title, author; public String gettitle() return title; public void settitle(string title) this.title = title; public String getauthor() return author; public void setauthor(string author) this.author = author; public class BookTest public static void main(string[] args) Book b = new Book(); b.settitle("data structure"); b.setauthor(" 홍길동 ");

3. class Dice private int face; int roll() int face = (int)(math.random() * 6) + 1; return face; public class DiceTest public static void main(string[] args) Dice dice = new Dice(); System.out.println(" 주사위숫자 : " + dice.roll()); 4. class Point int x, y; public void set(int x, int y) this.x = x; this.y = y; public void print() System.out.println("("+x+","+y+")"); public class PointTest public static void main(string[] args) Point p = new Point(); p.set(10, 10); p.print(); 5. class Employee private String name; private int tel; private int sal; public void setname(string n) name = n; public void settel(int t) tel = t; public void setsal(int s) sal = s;

public String getname() return name; public int gettel() return tel; public int getsal() return sal; public class EmployeeTest public static void main(string[] args) Employee em = new Employee(); 6. class BankAccount int accountnumber; String owner; int balance; void deposit(int amount) balance += amount; void withdraw(int amount) balance -= amount; public String tostring() return " 현재잔액은 " + balance + " 입니다."; public int transfer(int amount, BankAccount otheraccount) otheraccount.deposit(amount); return (balance-amount); public class BankAccountTest public static void main(string[] args) BankAccount myaccount1 = new BankAccount(); BankAccount myaccount2 = new BankAccount(); myaccount1.deposit(10000); System.out.println("myAccount1 : " +myaccount1); myaccount1.withdraw(8000); System.out.println("myAccount1 : " + myaccount1); System.out.println("myAccount2 : " + myaccount2); int b = myaccount1.transfer(1000, myaccount2); myaccount1.withdraw(b); System.out.println("myAccount1 : " + myaccount1); System.out.println("myAccount2 : " + myaccount2); 7. class Average public int getaverage(int a, int b) return (a+b)/2; public int getaverage(int a, int b, int c) return (a+b+c)/2;

public class AverageTest public static void main(string[] args) Average a = new Average(); System.out.println(a.getAverage(10, 20)); System.out.println(a.getAverage(10, 20, 30)); 78.5398 31.41592 p.205 1. MyClass 2. 생성자는반환형이없다. 3. 기존생성자호출 p.210 1. 정적변수는클래스의모든객체들에의해공유될때사용하는것이좋다. 2. 정적변수와정적메소드는객체를생성할필요가없고매개변수를통하여전달된값만있으면되므로클래스이름을통하여접근한다. 3. main() 메소드도정적메소드이기때문 p.213 1. 필드를다른클래스가직접사용하지못하게하기위해서 2. 디폴트로 package 가된다. 즉같은패키지에속하는클래스들은자유롭게사용할수있다. p.214 1. 자기자신을참조하는데사용된다. 2. 자신의생성자호출한다. p.217 1. 사용관계는하나의클래스가다른클래스를사용하는것이고, 집합관계는하나의클래스가다른클래스를포함하는것이다.

1. public class Circle private double radius; static final double PI=3.141592; // PI 라는이름으로 3.141592 로초기화된정적상수 (1) public Circle(double r) radius = r; (2) public double getradius() return radius; public void setradius(double radius) this.radius = radius; (3) private double square(double value) return value*value; (4) public double getarea() return square(radius)*pi; (5) public double getperimeter() return 2.0*PI*radius; (6) public static double getpi() return PI; (7) square() 함수는정적함수가아니라서 main() 에서호출하면오류가발생한다. (8) getpi() 함수는정적함수이므로 main() 에서호출할수있다. (9) class Circle private double radius; static final double PI=3.141592; // PI 라는이름으로 3.141592 로초기화된정적상수 public Circle(double r) radius = r;

public double getradius() return radius; public void setradius(double radius) this.radius = radius; private double square(double value) return value*value; public double getarea() return square(radius)*pi; public double getperimeter() return 2.0*PI*radius; public static double getpi() return PI; public class CircleTest public static void main(string args[]) Circle c = new Circle(5.0); // 객체생성, 생성자호출시반지름을 5.0 으로설정 System.out.println(c.getArea());// 원의면적계산하여출력 System.out.println(c.getPerimeter());// 원의둘레계산하여출력 1. (1) 객체가생성될때에필드에게초기값을제공하고필요한초기화절차를실행 (2) 매개변수의자료형이나매개변수개수로구별되어호출 (3) 자기자신을참조 (4) 정적변수는하나의클래스에하나만존재하여그클래스의모든객체들에의해공유되지만인스턴스변수는각인스턴스마다별도로생성된다. (5) 객체의참조값이전달된다. (6) 정적메소드는객체가생성되지않은상태에서호출되는메소드이므로객체안에서존재하는인스턴스변수들은사용할수없다. 2. (1) 생성자 Point() 는값을반환하지않는다따라서 void 를삭제한다. (2) 메소드의반환형이다르다고해서메소드를중복시킬수있는것은아니다. class MyMath public int getrandom1() return (int)math.random(); public double getrandom() return Math.random();

(3) 정적메소드 getstringname() 에서인스턴스메소드 getname() 을호출할수없다. class MyClass private static String getname() return "Myclass"; public static String getclassname() return getname(); 3. (1) public class Cube private double side; public Cube() side = 0; public double getside() return side; public double getvolume() return side*side*side; (2) public class Cube private double side; public Cube() side = 0; public Cube(double side) this.side = side; public double getside() return side; public double getvolume() return side*side*side; // 정육면체의한변 // 정육면체의한변 4. class MyMetric private static double distance; public static double kilotomile(double d) distance = d / 1.6093; return distance; public static void miletokilo(double d) distance = d * 1.6093;

public class MyMetricTest public static void main(string args[]) double d = MyMetric.kiloToMile(1); System.out.println(d); 5. s_instance 가 null 일때만객체를생성하고이미객체가생성되어있으면단순히객체의참조값을반환한다. class Single private static Single s_instance; public static Single getinstance() if (s_instance == null) s_instance = new Single(); return s_instance; 1. Dog -name : String -breed : String -age : int +getname() +getbreed() +getage() +setname() +setbreed() +setage() public class Dog private String name; private String breed; private int age; public Dog(String name, int age) this.name = name; this.age = age; public Dog(String name, String breed, int age) this.name = name; this.breed = breed;

this.age = age; public String getname() return name; public String getbreed() return breed; public int getage() return age; public void setname(string n) name = n; public void setbreed(string b) breed = b; public void setage(int a) age = a; 2. class Plane private int num, p_num; private String model; private static int planes; public void setnum(int n) num = n; public void setpnum(int pn) p_num = pn; public void setmodel(string m) model = m; public int getnum() return num; public int getpnum() return p_num; public String getmodel() return model; public static void setplanes(int p) planes = p;

public static int getplanes() return planes; public Plane() public Plane(int n, String m, int pn) num = n; p_num = pn; model = m; public Plane(int n, String m) num = n; model = m; public String tostring() return " 식별번호 :" + getnum() + " 모델 : " + getmodel() + " 승객수 : " + getpnum(); public class PlaneTest public static void main(string[] args) Plane plane1 = new Plane(1, "aa", 200); Plane plane2 = new Plane(2, "bb"); Plane plane3 = new Plane(); plane1.setplanes(0); plane1.getplanes(); plane3.setnum(3); plane3.setmodel("cc"); plane3.setpnum(150); 3. public class Box private int width, length, height; private boolean empty = false; public int getwidth() return width; public void setwidth(int width) this.width = width; public int getlength() return length; public void setlength(int length) this.length = length; public int getheight() return height; public void setheight(int height)

this.height = height; public boolean isempty() return empty; public void setempty(boolean empty) this.empty = empty; public Box() width = 0; length = 0; height = 0; empty = true; public Box(int w, int l, int h) width = w; length = l; height = h; empty = true; 4. public class Movie private String title; private String direction; private String company; public Movie() public Movie(String t, String d, String c) title = t; direction = d; company = c; 5. public class BankAccount private String ownername; private int accountnumber; private int balance; private double rate; public String getownername() return ownername; public void setownername(string ownername) this.ownername = ownername; public int getaccountnumber() return accountnumber;

public void setaccountnumber(int accountnumber) this.accountnumber = accountnumber; public int getbalance() return balance; public void setbalance(int balance) this.balance = balance; public double getrate() return rate; public void setrate(double rate) this.rate = rate; public BankAccount() public BankAccount(String n, int a, int b, double r) ownername = n; accountnumber = a; balance = b; rate = r; p.230 1. int[] array = new int[100]; 2. 0 에서 9 사이의정수 3. 예외 ( 오류 ) 가발생한다. 4. double[] array = 1.2, 3.1, 6.7 ; 5. for(i=0;i<array.length;i++) array[i] = 2 * array[i]; 6. Scanner scan=new Scanner(System.in); System.out.println( 배열의크기 : );

int size = scan.nextint(); int[] array = int[size]; 7. for-each 와전통적인 for 루프를비교하라. for-each 루프는배열의크기에신경쓰지않아도되고인덱스변수를생성할필요없이배열의첫번째원소부터마지막원소의값을꺼내서처리하는경우에사용한다. 하지만역순으로배열원소를처리하거나일부원소만처리하는경우는 for 루프를사용한다. 전통적인 for 루프를사용하면배열의원소를변경할수있지만 for-each 보다불편할수있다. 뒤에서학습하는컬렉션에서는 for-each 구조가무척편리하다. 8. 배열의크기가동일하다고가정하자. for(i=0;i<length;i++) array2[i] = array1[i]; 9. 배열의참조값이전달된다. 10. 배열원소는값이전달되고배열은참조가전달된다. p.232 1. BankAccount[] bank = new BankAccount[3]; for(int i =0; i < bank.lengh; i++) bank[i] = new BankAccount(); 2. 참조값이전달된다. p.234 1. Book[][] library = new Book[8][100]; 2. 2 차원배열객체를가리키는참조값이전달된다. 1. class Employee String name; // 직원의이름 public String getname() return name; public void setname(string name) this.name = name; public String getaddress() return address; public void setaddress(string address) this.address = address; public int getsalary() return salary;

2. public void setsalary(int salary) this.salary = salary; public String getphone() return phone; public void setphone(string phone) this.phone = phone; String address; // 주소 int salary; // 연봉 String phone; // 전화번호 import java.util.scanner; class Employee String name; // 직원의이름 public String getname() return name; public void setname(string name) this.name = name; public String getaddress() return address; public void setaddress(string address) this.address = address; public int getsalary() return salary; public void setsalary(int salary) this.salary = salary; public String getphone() return phone; public void setphone(string phone) this.phone = phone; String address; // 주소 int salary; // 연봉 String phone; // 전화번호

public class EmployeeTest public static void main(string args[]) Scanner scan = new Scanner(System.in); // 크기가 3 인 Employee 의배열 employees 을생성한다. Employee[] employees = new Employee[3]; // 3 명의사원정보를받아서각각 Employee 객체를생성한후에배열에추가하여본다. 반복루프를사용한다. for (int i = 0; i < employees.length; i++) employees[i] = new Employee(); for (int i = 0; i < employees.length; i++) System.out.println(" 이름 : "); employees[i].name = scan.next(); System.out.println(" 주소 : "); employees[i].address = scan.next(); // employees 배열에저장된모든데이터를출력한다. 반복루프를사용한다. for (int i = 0; i < employees.length; i++) System.out.println(" 이름 : " + employees[i].name); System.out.println(" 주소 : " + employees[i].address); 1. (1) int[] studentnumbers = new int[30]; (2) double[] values = 1.2, 3.3, 6.7; 2. (1) int[] numbers = new int[100]; (2) double[] rainfalls = new double[100]; 3. (1) 0 부터 4 까지 (2) 실시간오류발생 4. for(int i = 0; i < values.length; i++) values[i] = 0; 5. int[] a = 1, 2, 3, 4, 5; int[] b = new int[5]; for(int i = 0; i < a.length; i++) b[i] = a[i];

6. String[] employees = new String[10]; String name = " 홍길동 "; employees[0] = name; name = null; 배열의원소중에서 0 번째를제외하고나머지원소들은초기화가안되었다. 따라서 9 개의 null 참조가배열 employees[] 안에존재한다. 1. import java.util.scanner; class Theater int[] seats; int size; public Theater(int size) this.size=size; seats = new int[size]; public void print() System.out.println("----------------------------"); for(int i=0; i<size; i++) System.out.print(i+" "); System.out.println("\n----------------------------"); for(int i=0; i<size; i++) System.out.print(seats[i]+" "); System.out.println("\n----------------------------"); public void reserve() System.out.println(" 몇번째좌석을예약하시겠습니까?"); Scanner scan = new Scanner(System.in); int s = scan.nextint(); if( seats[s] == 0 ) seats[s] = 1; System.out.println(" 예약되었습니다."); public class TheaterTest public static void main(string args[]) Theater t = new Theater(10); t.print(); t.reserve(); t.print();

2. import java.util.scanner; class Histogram int[] freq; int size; public Histogram(int size) this.size = size; freq = new int[size]; public void print() for(int i=0; i<size; i++) System.out.print((i*10+1)+"-"+(i+1)*10); for(int k=0; k<freq[i]; k++) System.out.print("*"); System.out.println(""); public void input() System.out.println(" 점수를입력하시오 "); Scanner scan = new Scanner(System.in); int s = scan.nextint(); if( s!= 0 ) freq[(s-1)/10]++; else freq[0]++; public class HistogramTest public static void main(string args[]) Histogram t = new Histogram(10); for(int i=0;i<10;i++) t.input(); t.print(); 3. import java.util.scanner; public class ScoreTest static int[] num = new int[5]; static int sum =0; static double avg; public static void main(string[] args) Scanner s = new Scanner(System.in); for(int i=0; i<5; i++) System.out.println(" 성적을입력하세요 "); num[i] = s.nextint(); gettotal(); getaverage();

private static void getaverage() avg = sum / 5.0; System.out.println(" 평균 : "+avg); private static void gettotal() for(int i =0; i < 5; i++) sum += num[i]; System.out.println(" 합계 : "+sum); 4. import java.util.scanner; class Hexa2Bin String[] hexa2bin = "0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"; public void print(string s) for(int i=0;i<s.length();i++) char c = s.charat(i); int index = 0; if( c >='0' && c <='9') index = (c - '0'); if( c >='a' && c <='f') index = 10 + (c - 'a'); System.out.print(hexa2bin[index]+" "); System.out.print(""); public class HistogramTest public static void main(string args[]) Hexa2Bin t = new Hexa2Bin(); t.print("1abc"); p.230 1. 컴퓨터가수퍼클래스, 데스크탑, 노트북, 태블릿이모두서브클래스가된다.

컴퓨터 데스크탑노트북태블릿 2. 상속은코드를재사용하며코드의중복을줄인다. p.246 1. sleep() 과 eat() 가수퍼클래스에서만정의되므로코드가간결해진다. 2. class Box int width, length, height; public int calvolume() return width*height*height; class ColorBox extends Box String color; import java.util.scanner; class Human private String name; private int age; public String getname() return name; public void setname(string name) this.name = name; public int getage() return age; public void setage(int age) this.age = age; @Override public String tostring() return "Human [name=" + name + ", age=" + age + "]"; public String getprofession() return "unknown";

public Human(String name, int age) super(); this.name = name; this.age = age; class Student extends Human @Override public String tostring() return super.tostring() + "Student [major=" + major + "]"; public String getprofession() return "student"; String major; public Student(String name, int age, String major) super(name, age); this.major=major; public String getmajor() return major; public void setmajor(string major) this.major = major; public class StudentTest public static void main(string args[]) Student s1 = new Student(" 명진 ", 21, " 컴퓨터 "); Student s2 = new Student(" 미현 ", 22, " 경영 "); Student s3 = new Student(" 용준 ", 24, " 경제 "); 1. (1) Student, GraduateStudent (2) Student -number: int +name : String

GraduateStudent +lab : String (3) class Student public int getnumber() return number; public void setnumber(int number) this.number = number; public String getname() return name; public void setname(string name) this.name = name; private int number; public String name; public class GraduateStudent extends Student public String getlab() return lab; public void setlab(string lab) this.lab = lab; public String lab; (4) class Student public Student(int number, String name) super(); this.number = number; this.name = name;... private int number; public String name; public class GraduateStudent extends Student public GraduateStudent(int number, String name, String lab) super(number, name); this.lab = lab;

... public String lab; (5) (1) private 멤버는접근할수없다. 2. (1) methodtwo() (2) methodfour() (3) methodone() 과 methodthree() 는컴파일오류를발생한다. 인스턴스메소드를정적메소드로재정의할수는없다. 그반대도마찬가지이다. 3. class Bike protected int gear; public int speed; public class MountainBike extends Bike public int seatheight; public MountainBike(int g) super(); gear=g; 4. 동물입니다 :Brave 사자입니다. 동물입니다 :UNKNOWN 사자입니다. 1. class Circle double radius; String color; public Circle(double radius) super(); this.radius = radius; public Circle() super();

this.radius = 0; public double getradius() return radius; public void setradius(double radius) this.radius = radius; public double getarea() return 3.141592 * radius * radius; class Cylinder extends Circle public Cylinder(double radius, double height) super(radius); this.height = height; public Cylinder() super(0); public Cylinder(double radius) super(radius); public double getvolume() return super.getarea() * height; public double getheight() return height; public void setheight(double height) this.height = height; double height; public class TestCylinder public static void main(string[] args) Cylinder obj1 = new Cylinder(); System.out.println(obj1.getHeight()); System.out.println(obj1.getRadius()); Cylinder obj2 = new Cylinder(5.0, 3.0); System.out.println(obj2.getHeight()); System.out.println(obj2.getRadius());

2. class Person public Person(String name, String address) super(); this.name = name; this.address = address; public Person(String name, String address, String phone) super(); this.name = name; this.address = address; this.phone = phone; public String getname() return name; public void setname(string name) this.name = name; public String getaddress() return address; public void setaddress(string address) this.address = address; public String getphone() return phone; public void setphone(string phone) this.phone = phone; String name; String address; String phone; class Customer extends Person public Customer(String name, String address, int customernumber, int mileage) super(name, address); this.customernumber = customernumber; this.mileage = mileage; public Customer(String name, String address, String phone) super(name, address, phone);

int customernumber; int mileage; public class Test public static void main(string[] args)... 3. class Shape protected int x, y; protected int w, h; public double getarea() return 0; public double getperimeter() return 0; class Triangle extends Shape int a, b, c; public Triangle(int a, int b, int c) super(); this.a = a; this.b = b; this.c = c; @Override public double getarea() return 2.0 * w * h; @Override public double getperimeter() return a + b + c; public class Test public static void main(string[] args)... 4.

Book -title -pages -writer +gettitle() +settitle() +getpages() +setpages() +getwriter() +setwriter() +tostring <- class Book private String title; private int pages; private String writer; Magazine -date +getdate() +setdate() +main() public Book(String title,int pages,string writer) this.title=title; this.pages=pages; this.writer=writer; public String gettitle() return title; public void settitle(string title) this.title=title; public int getpages() return pages; public void setpages(int pages) this.pages=pages; public String getwriter() return writer; public void setwriter(string writer) this.writer=writer; public String tostring() return " 책이름 : "+title+"\n 페이지수 : "+pages+"\n 저자 : "+writer; public class Magazine extends Book private String date; public Magazine(String title,int pages,string writer,string date) super(title,pages,writer);

this.date=date; public String tostring() return super.tostring()+"\n발매일 :"+date; public static void main(string[] args) Magazine 잡지A = new Magazine(" 잡지A",10," 기자A","2010년 2월 25일 "); Magazine 잡지B = new Magazine(" 잡지B",20," 기자B","2010년 3월 8일 "); System.out.println( 잡지 A.toString()); System.out.println( 잡지 B.toString()); 5. 음식을나타내는 Food 클래스를상속받아멜론을나타내는 Melon 클래스를작성. Food 클래스는칼로리, 가격, 중량등의정보를가진다. Melon 클래스는추가로경작농원정보를가진다. (UML 을그린다.) Melon_Test +main() : void class Food private int cal; private int cost; private int kg; Melon ->Food -info : string +getinfo() : string +setinfo() : void +tostring(): string // 필드데이터정의 Food -cal : int -cost : int -kg : int +getcal() : int +getcost() : int +getkg() : int +setcal() : void +setcost() : void +setkg() :void public Food(int cal, int cost, int kg) // 생성자매개변수존재 this.cal = cal; this.cost = cost; this.kg = kg; public Food() this.cal = 0; this.cost = 0; this.kg = 0; // 생성자 public void setcal(int cal) // 설정자. this.cal = cal; public void setcost(int cost) this.cost = cost; public void setkg(int kg)

this.kg = kg; public int getcal() // 접근자. return cal; public int getcost() return cost; public int getkg() return kg; class Melon extends Food //melon 클래스작성 Food 상속 private String info; // 필드정의 public Melon(int cal, int cost, int kg,string info) super(cal, cost, kg); this.info = info; public Melon() super(); info = "NULL"; //Food 상속생성자작성 //Food 생성자호출 public void setinfo(string info) // 설정자. this.info = info; public String getinfo() // 접근자. return info; public String tostring() return "Melon 의정보 \n 칼로리 : "+this.getcal()+"\n 가격 : "+ this.getcost()+"\n 중량 : "+this.getkg()+"\n 정보 "+this.getinfo(); public class Melon_Test public static void main(string[] args) // 드라이버클래스작성 Melon m1 = new Melon(124,21,2,"jjh_fram"); Melon m2 = new Melon(1,1,1,"0"); m2.setcal(100); m2.setcost(210); m2.setkg(21); m2.setinfo("jjh2_test"); System.out.println(m1+"\n"); System.out.println(m2); 6. class Phone public Phone(String maker, int price, int type) super(); this.maker = maker; this.price = price; this.type = type; public String getmaker() return maker; public void setmaker(string maker) this.maker = maker;

public int getprice() return price; public void setprice(int price) this.price = price; public int gettype() return type; public void settype(int type) this.type = type; protected String maker; protected int price; protected int type; class SmartPhone extends Phone public String getos() return os; public SmartPhone(String maker, int price, int type, String os, String version, int memory, boolean hascamera, boolean hasbluetooth) super(maker, price, type); this.os = os; this.version = version; this.memory = memory; this.hascamera = hascamera; this.hasbluetooth = hasbluetooth; public void setos(string os) this.os = os; public String getversion() return version; public void setversion(string version) this.version = version; public int getmemory() return memory; public void setmemory(int memory) this.memory = memory; public boolean ishascamera() return hascamera; public void sethascamera(boolean hascamera) this.hascamera = hascamera; public boolean ishasbluetooth() return hasbluetooth;

public void sethasbluetooth(boolean hasbluetooth) this.hasbluetooth = hasbluetooth; private String os; private String version; private int memory; private boolean hascamera; private boolean hasbluetooth; public class Test public static void main(string[] args)... 7. class Student private String name; private int number; private String major; private int grade; private int next_point; 같기에 //Student 클래스정의 // 필드데이터정의 // 이름, 학번, 전공, 학년, 학점 // 생성자정의 public Student(String name,int number,string major,int grade,int next_point) this.name = name; // 매개변수와필드데이터이름이 this.number = number; //this. 사용자신의클래스변수를참조 this.major = major; this.grade = grade; this.next_point = next_point; public Student() name = null; number = 0; major = null; grade = 0; next_point = 0; 저장 public String getname() // 접근자를설정한다. return name; // 외부서접근자를통해해당데이터 public int getnumber() return number; public String getmajor() return major; public int getgrade() return grade; public int getnext_point() return next_point; public void setname(string name) // 설정자정의 this.name = name; // 설정자를통해클래스데이터변경가

능 public void setnumber(int number) this.number = number; public void setmajor(string major) this.major = major; public void setgrade(int grade) this.grade = grade; public void setnext_point(int next_point) this.next_point = next_point; public String tostring() //tostring 재정의한다. 클래스정보를출력 return " 이름 :"+name+" 학번 :"+number+" 학과 :"+major+" 학년 :"+ grade+" 이수학점 :"+next_point; class undergraduate extends Student // 학부생클레스정의 Stduent 로부터상속받음. private String club; // 필드데이터정의 " 동아리이름 " // 생성자정의 public undergraduate(string name, int number, String major, int grade, int nextpoint, String club) super(name, number, major, grade, nextpoint); //super 통해부모클래스생성자호출 this.club = club; public undergraduate() super(); club = null; public void setclub(string club) this.club = club; public String getclub() return club; // 생성자설정 // 접근자설정 //tostring 재정의한다. 학부생클래스정보출력 public String tostring() return " 이름 :"+getname()+"/ 학번 :"+getnumber()+"/ 학과 :"+getmajor()+ "/ 학년 :"+getgrade()+"/ 이수학점 :"+getnext_point() + "/ 소속동아리 :"+club; class Graduate extends Student private String assistant ; // 교육조교 private boolean scholarship; // 장학금여부 // 생성자를정의한다. public Graduate(String name, int number, String major, int grade, int nextpoint,string assistant, int scholarship) super(name, number, major, grade, nextpoint); //super 사용부모클래스생성자호출 this.assistant = assistant; this.scholarship = ((scholarship == 1)? true:false); // 입력값을확인 //1일경우 true 그외일경우 false 저장 public Graduate() super(); assistant = null; scholarship = false;

public void setassistant(string assistant) this.assistant = assistant; public void setscholarship(boolean scholarship) this.scholarship = scholarship; public String getassistant() return assistant; public boolean getscholarship() return scholarship; // 설정자정의 // 접근자정의 //tostring 재정의대학원생클래스의정보를출력 public String tostring() return " 이름 :"+getname()+"/ 학번 :"+getnumber()+"/ 학과 :"+getmajor()+ "/ 학년 :"+getgrade()+"/ 이수학점 :"+getnext_point() + "/ 조교유형 :"+assistant+"/ 장학금여부 :"+((scholarship == true)? " 받음 ":" 못받음 "); public class student_test public static void main(string[] args) "); 가능. 출 ) 경변경 undergraduate ug1 = new undergraduate(" 갑 ",1000," 컴공 ",3,84," 날자날어 Graduate g1 = new Graduate(" 을 ", 100, " 전자공학 ", 2, 51," 교육조교 ",0); Graduate g2 = new Graduate(" 병 ", 100, " 세포생물 ", 2, 61," 연구조교 ",1); // 대학원생객체를두개생성 g1,g2 를통해참조 System.out.println(ug1); //ug1 이가르키는객체정보를출력 (tostring 호 ug1.setclub(" 돌고돌아 "); //ug1 이가르키는객체클럽설정자호출, 값변 ug1.setnext_point(87); System.out.println(ug1); //ug1 이가르키는객체학점설정자호출, 데이터 //ug1 이가르키를객체정보를출력 System.out.println(g1); //g1 이가르키를객체정보를출력 경 변경 g2.setgrade(3); g2.setnumber(102); //g2가가르키는객체학년설정자를호출, 값변 //g2가가르키는객체학번설정자를호출, 값 System.out.println(g2); //g2 의객체정보를다시출력

p.269 1. 주로상속계층에서추상적인개념을나타내기위한용도로사용 2. 추상클래스는일반메소드도포함한다 3. 반드시추상메소드를구현해야한다. p.277 1. 객체와객체사이의상호작용을위하여사용 2. 하나의클래스는여러개의인터페이스를동시에구현할수있다. 3. 선언할수없다. p.279 1. 인터페이스도클래스와마찬가지로타입이라고생각할수있다. 따라서참조변수를정의하는데사용될수있다 2. 여러클래스에서사용되는상수를정의하면그인터페이스를구현하는클래스들은자동적으로인터페이스에정의된상수들을공유하게된다. 3. 인터페이스를사용하여다중상속의효과를낸다. p.287 1. 수퍼클래스참조변수가서브클래스객체를참조하는것은가능하지만, 서브클래스의참조변수가수퍼클래스의객체를참조하는것은문법적인오류이다. 2. A instanceof B 일때, 객체 A 가클래스 B 로생성되었으면 true 를반환 3. 동일한수퍼클래스에서상속된서브클래스의객체들을하나의타입으로취급할때유용하다 4. 수퍼클래스타입으로선언하는것이좋다 p.289 1. 내부클래스는하나의클래스안에다른클래스를정의하는것으로클래스의모든멤버를참조할수있다. 2. 내부클래스는 private 로선언된필드도접근이가능하다. p.291 1. new 키워드다음에수퍼클래스이름이나인터페이스이름을적어준다 2. 무명클래스를정의하면클래스정의와객체생성을동시에할수있다. 3. new Object()...

import java.awt.event.actionevent; import java.awt.event.actionlistener; import javax.swing.timer; public class CallbackTest public static void main(string[] args) ActionListener listener = new MyClass(); Timer t = new Timer(1000, listener); t.start(); for (int i = 0; i < 1000; i++) try Thread.sleep(1000); catch (InterruptedException e) class MyClass implements ActionListener @Override public void actionperformed(actionevent e) // TODO Auto-generated method stub System.out.println("beep"); 1. class AudioSystem extends SoundSystem implements MP3playable, TurnTableplayable... 2. 인터페이스안에는추상메소드만정의할수있다. public interface MyInterface void MyMethod(int value);

3. abstract class Bird abstract public void sound(); class Dove extends Bird public void sound() System.out.println("coo coo"); 4. public interface Edible //boolean amount; 필드는정의할수없다. final int TYPE=10; public void eat(); // ; 추상메소드만정의할수있다. ; public class Sandwitch implements Edible public void eat() 5. (2) 6. (3) 7. a, b, c, d 9. (1) 수퍼클래스참조변수는서브클래스객체를가리킬수있다. (2) 가능하다. (3) 오타! 다음과같은문장은적법한가? 그이유는? Point3D p = new Point2D(); -> 적법하지않다. 수퍼클래스객체를서브클래스참조변수로가리킬수없다. (4) class Point2D public int getx() return x; public void setx(int x) this.x = x; public int gety() return y; public void sety(int y) this.y = y; private int x; private int y; class Point3D extends Point2D public int getz() return z;

public void setz(int z) this.z = z; private int z; 1. interface Movable void move(int dx, int dy); class Shape implements Movable protected int x, y; public void draw() System.out.println("Shape Draw"); ; public void move(int dx, int dy) x = dx; y = dy; class Rectangle extends Shape private int width, height; ; public void setwidth(int w) width = w; public void setheight(int h) height = h; public void draw() System.out.println("Rectangle Draw"); class Triangle extends Shape private int base, height;

public void draw() System.out.println("Triangle Draw"); ; @Override public void move(int dx, int dy) x = dx; y = dy; class Circle extends Shape private int radius; ; public void draw() System.out.println("Circle Draw"); public class ShapeTest private static Movable arrayofshapes[]; public static void main(string arg[]) init(); moveall(); public static void init() arrayofshapes = new Shape[3]; arrayofshapes[0] = new Rectangle(); arrayofshapes[1] = new Triangle(); arrayofshapes[2] = new Circle(); ; public static void moveall() for (int i = 0; i < arrayofshapes.length; i++) arrayofshapes[i].move(10, 10); 2. 오타! 다음과같이수정하여주세요. 다음과같은인터페이스들을정의하라. public interface Drawable void draw(); 본문의 ShapeTest.java 에등장하는 2 차원도형인원, 사각형, 삼각형등이위의인터페이스를구현하도록수정하라. draw() 메소드에서는실제로그리지는않고메시지만을출력하라. main() 에서 Drawable 객체배열을생성하고배열의각원소에대하여 draw() 를호출하는프로그램을작성하라.

interface Drawable void draw(); class Shape implements Drawable protected int x, y; ; public void draw() System.out.println("Shape Draw"); class Rectangle extends Shape private int width, height; ; public void setwidth(int w) width = w; public void setheight(int h) height = h; public void draw() System.out.println("Rectangle Draw"); class Triangle extends Shape private int base, height; ; public void draw() System.out.println("Triangle Draw"); class Circle extends Shape private int radius; ; public void draw() System.out.println("Circle Draw"); public class ShapeTest private static Drawable arrayofshapes[]; public static void main(string arg[]) init(); drawall();

public static void init() arrayofshapes = new Shape[3]; arrayofshapes[0] = new Rectangle(); arrayofshapes[1] = new Triangle(); arrayofshapes[2] = new Circle(); ; public static void drawall() for (int i = 0; i < arrayofshapes.length; i++) arrayofshapes[i].draw(); 3. interface controllable void play(); void stop(); public class Test public static void main(string arg[]) controllable c = new controllable() public void play() System.out.println("PLAY"); public void stop() System.out.println("STOP"); ; ; c.play(); c.stop(); 4. interface Comparable // 이객체가다른객체보다크면 1, 같으면 0, 작으면 -1 을반환한다. int compareto(object other); class Person implements Comparable @Override public String tostring() return "Person [name=" + name + ", height=" + height + "]"; public Person(String name, double height) super(); this.name = name; this.height = height; String name;

double height; @Override public int compareto(object other) if ( this.height > ((Person)other).height ) return 1; else if ( this.height == ((Person)other).height ) return 0; else return -1; public class Test public static Person getmaximum(person[] array) Person max=array[0]; for(int i=1;i<array.length;i++) if( array[i].height > max.height ) max = array[i]; return max; public static void main(string arg[]) Person[] array; array = new Person[3]; array[0] = new Person(" 홍길동1", 190); array[1] = new Person(" 홍길동2", 180); array[2] = new Person(" 홍길동3", 185); System.out.println(getMaximum(array)); 5. 생략 6. 생략 p.306 1. 컴포넌트

2. AWT 는운영체제에서제공하는컴포넌트를그대로사용한것이다. 스윙은자바가직접각컴포넌트를작성한것이다. 3. 스윙에서기본적으로제공된다. 4. setvisible() 메소드는 Window 클래스에서제공한다. 따라서 Window 를상속받는클래스들이사용할수있다. 예를들어서 JFrame 클래스가사용할수있다. p.308 1. 다른컴포넌트들을내부에넣을수있는기능을가진다. 2. 절대다른컨테이너안에포함될수없는컨테이너로프레임, 다이알로그, 애플릿이있다. p.313 1. 프레임객체생성 -> 버튼생성 -> 버튼을프레임에추가 2. class MyFrame extends JFrame public MyFrame()... JButton button1 = new JButton(" 버튼 1"); JButton button2 = new JButton(" 버튼 2"); this.add(button1); this.add(button2); p.323 1. class MyFrame extends JFrame public MyFrame()... JLabel label = new JLabel(" 레이블 "); JButton button = new JButton(" 버튼 "); this.add(label); this.add(button); 2. 패널에버튼을추가하면버튼 3 개가나란히보이지만, 프레임에버튼 3 개를추가하면마지막버튼만프레임전체에보인다. 1. (1) JButton (2) 버튼, 레이블, 텍스트필드등 (3) JFrame 클래스를확장하여야한다. (4) 화면에표시되어서사용자와상호작용하는시각적인객체를나타내며 add(), getwidth(), getx(), setfont() 등이사용된다.

(5) 컨테이너생성 -> 컴포넌트생성 -> 컴포넌트를컨테이너에추가 2. (1) 거짓 - 패널은다른패널을포함할수있다. (2) 거짓 - 스윙의컴포넌트수가 AWT 보다많다. (3) 거짓 - add() (4) 거짓 - 프레임은최상위컨테이너라다른컨테이너안에포함될수없다. 3. (1) import javax.swing.*; (2) button = new JButton(" 동작 "); (3) JButton button1, button2; (4) JLabel label = new JLabel(); 4. (1) JLabel, JButton, JPanel, JFrame (2) setsize(500,100); (3) JPanel panel = new JPanel(); (4) JLabel label = new JLabel(" 자바는재미있나요?"); (5) JButton button1 = new JButton("Yes"); JButton button2 = new JButton("No"); (6) panel.add(label); panel.add(button1); panel.add(button2); (7) add(panel); 1. import java.awt.*; import javax.swing.*; class TestFrame extends JFrame public TestFrame() setsize(500,100); setdefaultcloseoperation(jframe.exit_on_close); settitle(" 테스트프레임 "); JPanel panel = new JPanel(); JLabel label = new JLabel(" 자바는재미있나요?"); JButton button1 = new JButton("Yes"); JButton button2 = new JButton("No"); panel.add(label); panel.add(button1);

panel.add(button2); add(panel); setvisible(true); public class TestFrameT public static void main(string[] args) TestFrame f = new TestFrame(); 2. import java.awt.*; import javax.swing.*; class MyFrame extends JFrame public MyFrame() setsize(500,150); setdefaultcloseoperation(jframe.exit_on_close); settitle(" 테스트프레임 "); JPanel panel1 = new JPanel(); JLabel label1 = new JLabel(" 인간에게주어진최사의선물은마음껏웃을수있다는것이다."); JLabel label2 = new JLabel(" 가능한목표라고하더라도그것을꿈꾸고상상하는순간이미거기에다가가있는것이다. "); JLabel label3 = new JLabel(" 상상력은생존의힘이다."); panel1.add(label1); panel1.add(label2); panel1.add(label3); add(panel1); setvisible(true); public class MyFrameTest public static void main(string[] args) MyFrame f = new MyFrame(); 3. import java.awt.*; import javax.swing.*; class MyFrame extends JFrame public MyFrame() setsize(400,150);

setdefaultcloseoperation(jframe.exit_on_close); settitle(" 테스트프레임 "); JPanel panel1 = new JPanel(); JPanel panel2 = new JPanel(); JPanel panel3 = new JPanel(); JLabel label1 = new JLabel(" 자바호텔에오신것을환영합니다."); JLabel label2 = new JLabel(" 숙박일수를입력하세요."); JButton button1 = new JButton("1명 "); JButton button2 = new JButton("2명 "); JButton button3 = new JButton("3명 "); JButton button4 = new JButton("4명 "); JButton button5 = new JButton("5명 "); panel1.add(label1); panel1.add(label2); panel2.add(button1); panel2.add(button2); panel2.add(button3); panel2.add(button4); panel2.add(button5); panel3.add(panel1); panel3.add(panel2); add(panel3); setvisible(true); public class MyFrameTest public static void main(string[] args) MyFrame f = new MyFrame();

import java.awt.flowlayout; import javax.swing.jbutton; import javax.swing.jframe; import javax.swing.jpanel; class MyFrame extends JFrame JPanel p1; public MyFrame() setsize(300, 200); settitle("my Frame"); p1 = new JPanel(); p1.setlayout(new FlowLayout()); for (int i = 0; i < 10; i++) p1.add(new JButton("Button" + i)); add(p1); setvisible(true); // 프레임을화면에표시한다. public class MyFrameTest public static void main(string args[]) MyFrame f = new MyFrame(); 1. 마지막에추가한버튼이다른버튼들을전부가리게된다.

2. 3. GridLayout(1, 0) 4. import java.awt.color; import javax.swing.jframe; import javax.swing.jlabel; import javax.swing.jpanel; class MyFrame extends JFrame JPanel p = new JPanel(); JLabel[] labels = new JLabel[30]; public MyFrame() p.setlayout(null); for (int i = 0; i < 30; i++) labels[i] = new JLabel("" + i); int x = (int) (500 * Math.random()); int y = (int) (200 * Math.random()); labels[i].setforeground(color.magenta); labels[i].setlocation(x, y); labels[i].setsize(20, 20); p.add(labels[i]); setsize(500, 300); add(p); setvisible(true); // 프레임을화면에표시한다. public class MyFrameTest public static void main(string args[]) MyFrame f = new MyFrame();

1. // 패키지포함 import java.awt.gridlayout; import javax.swing.jbutton; import javax.swing.jframe; import javax.swing.jlabel; import javax.swing.jpanel; import javax.swing.jtextfield; // JFrame 을상속받는 MyFrame 클래스선언 class MyFrame extends JFrame // 필드선언 private JButton button; private JLabel label; private JTextField textinput,textresult; private JPanel panel,panel1,panel2,panel3; // 생성자선언 public MyFrame() setsize(500,200); // 프레임의크기설정 setdefaultcloseoperation(jframe.exit_on_close); // 종료버튼을눌렀을때프레임이닫히도록설정 settitle(" 마일을킬로미터로변환 "); // 프레임의제목설정

panel = new JPanel(); // panel 에패널객체생성 panel.setlayout(new GridLayout(0, 1)); panel1 = new JPanel(); // panel 에패널객체생성 panel2 = new JPanel(); // panel 에패널객체생성 panel3 = new JPanel(); // panel 에패널객체생성 객체생성 label= new JLabel(" 거리를마일단위로입력하세요 "); // label 에레이블 textinput = new JTextField(10); // textinput에텍스트필드객체생성 panel1.add(label); // 패널에레이블추가 panel1.add(textinput); // 패널에텍스트필드추가 button = new JButton(" 변환 "); // button 에버튼객체생성 panel2.add(button); // 패널에버튼추가 드객체생성 textresult = new JTextField(30); // textresult 에크기가 30 인텍스트필 panel3.add(textresult); // 패널에텍스트필드추가 panel.add(panel1); panel.add(panel2); panel.add(panel3); add(panel); // 프레임에패널추가 setvisible(true); // 프레임출력메소드 public class MyFrameTest public static void main(string[] args) MyFrame f = new MyFrame(); // 객체생성 2. import java.awt.gridlayout; import java.awt.event.*; import javax.swing.*;

class Myframe extends JFrame JButton button; JTextField t1; JTextField t2; JTextField t3; private JPanel panel,panel1,panel2,panel3, panel4; public Myframe() setsize(230,150); setdefaultcloseoperation(jframe.exit_on_close); settitle(" 이자계산기 "); JPanel panel=new JPanel(new GridLayout(0, 1)); JPanel panel1=new JPanel(); JPanel panel2=new JPanel(); JPanel panel3=new JPanel(); JPanel panel4=new JPanel(); JLabel label1=new JLabel(" 원금을입력하시오 "); t1=new JTextField(5); panel1.add(label1); panel1.add(t1); JLabel label2=new JLabel(" 이율을입력하시오 "); t2=new JTextField(5); panel2.add(label2); panel2.add(t2); button=new JButton(" 변환 "); panel3.add(button); t3=new JTextField(20); panel4.add(t3); panel.add(panel1); panel.add(panel2); panel.add(panel3); panel.add(panel4); this.add(panel); setvisible(true); public class MyFrameTest public static void main(string[] arge) Myframe f=new Myframe();

3. 오타! 문제의그림을다음과같이수정하여주세요. 윈도우제목 계산기 23 텍스트필드 C 7 8 9 / 4 5 6 * 버튼 1 2 3-0 +/- = + import java.awt.flowlayout; import java.awt.gridlayout; import javax.swing.boxlayout; import javax.swing.jbutton; import javax.swing.jframe; import javax.swing.jpanel; import javax.swing.jtextfield; class MyFrame extends JFrame public MyFrame() JPanel p, p1, p2, p3; JTextField tf; JButton[] b = new JButton[17]; p = new JPanel(); p.setlayout(new BoxLayout(p, BoxLayout.Y_AXIS)); p1 = new JPanel(); FlowLayout layout = new FlowLayout(); layout.setalignment(flowlayout.left); layout.setvgap(0); p1.setlayout(layout); p2 = new JPanel(); p2.setlayout(layout);

p3 = new JPanel(new GridLayout(0, 4)); tf = new JTextField(30); p1.add(tf); b[0] = new JButton("C"); b[1] = new JButton("7"); b[2] = new JButton("8"); b[3] = new JButton("9"); b[4] = new JButton("/"); b[5] = new JButton("4"); b[6] = new JButton("5"); b[7] = new JButton("6"); b[8] = new JButton("*"); b[9] = new JButton("1"); b[10] = new JButton("2"); b[11] = new JButton("3"); b[12] = new JButton("-"); b[13] = new JButton("0"); b[14] = new JButton("+/-"); b[15] = new JButton("="); b[16] = new JButton("+"); p2.add(b[0]); for (int i=1; i<17; i++) p3.add(b[i]); p.add(p1); p.add(p2); p.add(p3); add(p); setdefaultcloseoperation(jframe.exit_on_close); pack(); setvisible(true); public class MyFrameTest public static void main(string[] args) new MyFrame();

p.360 1. 오류 : 아직이벤트처리를학습하지않았는데문제가이벤트처리를요구하고있습니다. 다음과같이문제를변경하여주십시오. SnowManFace 에서찡그린얼굴을그리도록소스를수정하라. import java.awt.borderlayout; import java.awt.color; import java.awt.graphics; import java.awt.event.actionevent; import java.awt.event.actionlistener; import javax.swing.jbutton; import javax.swing.jframe; import javax.swing.jpanel; class MyPanel extends JPanel int type = 0; public void paintcomponent(graphics g) super.paintcomponent(g); if( type == 0 ) g.setcolor(color.yellow); g.filloval(20, 30, 200, 200); g.setcolor(color.black);

else g.drawarc(60, 80, 50, 50, 180, -180); // 왼쪽눈 g.drawarc(150, 80, 50, 50, 180, -180); // 오른쪽눈 g.drawarc(70, 130, 100, 70, 180, 180); // 입 g.setcolor(color.yellow); g.filloval(20, 30, 200, 200); g.setcolor(color.black); g.drawarc(60, 80, 50, 50, 180, +180); // 왼쪽눈 g.drawarc(150, 80, 50, 50, 180, +180); // 오른쪽눈 g.drawarc(70, 130, 100, 70, 180, 180); // 입 public int gettype() return type; public void settype(int type) this.type = type; repaint(); public class SnowManFace extends JFrame implements ActionListener MyPanel panel; public SnowManFace() setsize(280, 300); setdefaultcloseoperation(jframe.exit_on_close); settitle(" 눈사람얼굴 "); setvisible(true); panel = new MyPanel(); add(panel); JButton b = new JButton(" 찡그린얼굴 "); add(b, BorderLayout.SOUTH); b.addactionlistener(this); public static void main(string[] args) SnowManFace s = new SnowManFace(); @Override public void actionperformed(actionevent arg0) panel.settype(1);

2. 생략 p.368 1. mylabel.setfont(new Font("Dialog", Font.ITALIC, 10)); 1. import java.awt.graphics; import javax.swing.jcomponent; import javax.swing.jframe; class MyComponent extends JComponent // JComponent 를상속받은 MyComponent 클래스생성 public void paint(graphics g) // paint 메소드재정의 g.drawline(10, 80, 100, 10); // x, y좌표 10, 80부터 100, 10까지선긋기 g.drawstring("drawline()", 10, 100); // x, y 좌표 10, 100 에문자열그리기 g.drawrect(110, 10, 110, 80); // x, y 좌표 10, 80 부터 100, 10 까지사각형그리기 g.drawstring("drawrect()", 110, 100); // x, y 좌표 10, 100 에문자열그리기 // public class Test public static void main(string[] args)