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

Size: px
Start display at page:

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

Transcription

1 p 객체 , SIMULA p 데이터, 알고리즘 2. 데이터 3. 클래스를변경하기가쉬워진다. p 메시지 2. start(), stop(), speedup(int s), speeddown(int s), turnleft(int degree), turnright(int degree) p 클래스 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; // 재고수량 // 이름

2 public String breed; public String color; // 메소드정의 public void bark()... public void bite()... public void eat()... // 종 // 색깔 p 기초변수는 int, float, char 등의기초자료형을가지는변수이고, 참조변수는객체를참조할때사용되는변수이다. 2. 두개의참조변수가하나의객체를가리킨다. 3. 참조변수에 null 을대입한다. 예를들면 p = null; 와같다. p 기초형, 참조형 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();

3 (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 설명년도월일

4 동작 ( 행동 ) 메소드이름 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) = 5 (e) = 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());

5 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()

6 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.

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 크게나누면기초형변수와참조형변수가존재한다. 2. 잘못된값이저장되는것은사전에체크할수있고또필요할때마다값을다시계산하여서반환할수도있다. 3. 필드는클래스안에선언되는변수이다. 지역변수는메소드안에선언되어서메소드안에서만사용되는변수이다. p 중복메소드 (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

8 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()

9 (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) Box box1; box1 = new Box(); box1.setwidth(100); box1.setlength(100); box1.setheight(100); System.out.println(box1.getVolume()); (9) (10) 가로 :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

10 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;

11 (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: 이름, 주소, 소유한계좌번호

12 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 *r*r; public double getr() return r; public void setr(double r) this.r = r;

13 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(" 홍길동 ");

14 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;

15 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;

16 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)); p MyClass 2. 생성자는반환형이없다. 3. 기존생성자호출 p 정적변수는클래스의모든객체들에의해공유될때사용하는것이좋다. 2. 정적변수와정적메소드는객체를생성할필요가없고매개변수를통하여전달된값만있으면되므로클래스이름을통하여접근한다. 3. main() 메소드도정적메소드이기때문 p 필드를다른클래스가직접사용하지못하게하기위해서 2. 디폴트로 package 가된다. 즉같은패키지에속하는클래스들은자유롭게사용할수있다. p 자기자신을참조하는데사용된다. 2. 자신의생성자호출한다. p 사용관계는하나의클래스가다른클래스를사용하는것이고, 집합관계는하나의클래스가다른클래스를포함하는것이다.

17 1. public class Circle private double radius; static final double PI= ; // PI 라는이름으로 로초기화된정적상수 (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= ; // PI 라는이름으로 로초기화된정적상수 public Circle(double r) radius = r;

18 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();

19 (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 / ; return distance; public static void miletokilo(double d) distance = d * ;

20 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;

21 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;

22 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)

23 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;

24 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 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( 배열의크기 : );

25 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 BankAccount[] bank = new BankAccount[3]; for(int i =0; i < bank.lengh; i++) bank[i] = new BankAccount(); 2. 참조값이전달된다. p 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;

26 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; // 전화번호

27 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];

28 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();

29 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();

30 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 컴퓨터가수퍼클래스, 데스크탑, 노트북, 태블릿이모두서브클래스가된다.

31 컴퓨터 데스크탑노트북태블릿 2. 상속은코드를재사용하며코드의중복을줄인다. p 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 = public String tostring() return "Human [name=" + name + ", age=" + age + "]"; public String getprofession() return "unknown";

32 public Human(String name, int age) super(); this.name = name; this.age = age; class Student extends 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

33 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;

34 ... 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();

35 this.radius = 0; public double getradius() return radius; public void setradius(double radius) this.radius = radius; public double getarea() return * 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());

36 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);

37 int customernumber; int mileage; public class Test public static void main(string[] args) 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 = public double getarea() return 2.0 * w * public double getperimeter() return a + b + c; public class Test public static void main(string[] args)... 4.

38 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);

39 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)

40 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;

41 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;

42 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) 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; // 설정자를통해클래스데이터변경가

43 능 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;

44 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 의객체정보를다시출력

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

46 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 public void actionperformed(actionevent e) // TODO Auto-generated method stub System.out.println("beep"); 1. class AudioSystem extends SoundSystem implements MP3playable, TurnTableplayable 인터페이스안에는추상메소드만정의할수있다. public interface MyInterface void MyMethod(int value);

47 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;

48 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;

49 public void draw() System.out.println("Triangle Draw"); 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() 를호출하는프로그램을작성하라.

50 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();

51 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 public String tostring() return "Person [name=" + name + ", height=" + height + "]"; public Person(String name, double height) super(); this.name = name; this.height = height; String name;

52 double 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 컴포넌트

53 2. AWT 는운영체제에서제공하는컴포넌트를그대로사용한것이다. 스윙은자바가직접각컴포넌트를작성한것이다. 3. 스윙에서기본적으로제공된다. 4. setvisible() 메소드는 Window 클래스에서제공한다. 따라서 Window 를상속받는클래스들이사용할수있다. 예를들어서 JFrame 클래스가사용할수있다. p 다른컴포넌트들을내부에넣을수있는기능을가진다. 2. 절대다른컨테이너안에포함될수없는컨테이너로프레임, 다이알로그, 애플릿이있다. p 프레임객체생성 -> 버튼생성 -> 버튼을프레임에추가 2. class MyFrame extends JFrame public MyFrame()... JButton button1 = new JButton(" 버튼 1"); JButton button2 = new JButton(" 버튼 2"); this.add(button1); this.add(button2); p 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() 등이사용된다.

54 (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);

55 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);

56 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();

57 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. 마지막에추가한버튼이다른버튼들을전부가리게된다.

58 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();

59 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(" 마일을킬로미터로변환 "); // 프레임의제목설정

60 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.*;

61 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();

62 3. 오타! 문제의그림을다음과같이수정하여주세요. 윈도우제목 계산기 23 텍스트필드 C / * 버튼 /- = + 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);

63 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();

64 p 오류 : 아직이벤트처리를학습하지않았는데문제가이벤트처리를요구하고있습니다. 다음과같이문제를변경하여주십시오. 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);

65 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 public void actionperformed(actionevent arg0) panel.settype(1);

66 2. 생략 p 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)

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

(8) getpi() 함수는정적함수이므로 main() 에서호출할수있다. (9) class Circle private double radius; static final double PI= ; // PI 이름으로 로초기화된정적상수 public Chapter 9 Lab 문제정답 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

More information

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

gnu-lee-oop-kor-lec06-3-chap7 어서와 Java 는처음이지! 제 7 장상속 Super 키워드 상속과생성자 상속과다형성 서브클래스의객체가생성될때, 서브클래스의생성자만호출될까? 아니면수퍼클래스의생성자도호출되는가? class Base{ public Base(String msg) { System.out.println("Base() 생성자 "); ; class Derived extends Base

More information

PowerPoint Presentation

PowerPoint Presentation 객체지향프로그래밍 그래픽사용자인터페이스 ( 실습 ) 손시운 ssw5176@kangwon.ac.kr 예제 1. 프레임생성 (1) import javax.swing.*; public class FrameTest { public static void main(string[] args) { JFrame f = new JFrame("Frame Test"); JFrame

More information

PowerPoint Presentation

PowerPoint Presentation 객체지향프로그래밍 클래스, 객체, 메소드 ( 실습 ) 손시운 ssw5176@kangwon.ac.kr 예제 1. 필드만있는클래스 텔레비젼 2 예제 1. 필드만있는클래스 3 예제 2. 여러개의객체생성하기 4 5 예제 3. 메소드가추가된클래스 public class Television { int channel; // 채널번호 int volume; // 볼륨 boolean

More information

PowerPoint Presentation

PowerPoint Presentation 객체지향프로그래밍 인터페이스, 람다식, 패키지 ( 실습 ) 손시운 ssw5176@kangwon.ac.kr 예제 1. 홈네트워킹 public interface RemoteControl { public void turnon(); // 가전제품을켠다. public void turnoff(); // 가전제품을끈다. 인터페이스를구현 public class Television

More information

Microsoft PowerPoint - Lect04.pptx

Microsoft PowerPoint - Lect04.pptx OBJECT ORIENTED PROGRAMMING Object Oriented Programming 이강의록은 Power Java 저자의강의록을사용했거나재편집된것입니다. Class 와 object Class 와객체 클래스의일생 메소드 필드 String Object Class 와객체 3 클래스 클래스의구성 클래스 (l (class): 객체를만드는설계도 클래스로부터만들어지는각각의객체를특별히그클래스의인스턴스

More information

PowerPoint Presentation

PowerPoint Presentation 객체지향프로그래밍 클래스와메소드심층연구 ( 실습 ) 손시운 ssw5176@kangwon.ac.kr 예제 1. 접근제어 class A { private int a; int b; public int c; // 전용 // 디폴트 // 공용 public class Test { public static void main(string args[]) { A obj = new

More information

JAVA PROGRAMMING 실습 08.다형성

JAVA PROGRAMMING 실습 08.다형성 2015 학년도 2 학기 1. 추상메소드 선언은되어있으나코드구현되어있지않은메소드 abstract 키워드사용 메소드타입, 이름, 매개변수리스트만선언 public abstract String getname(); public abstract void setname(string s); 2. 추상클래스 abstract 키워드로선언한클래스 종류 추상메소드를포함하는클래스

More information

PowerPoint Presentation

PowerPoint Presentation 자바프로그래밍 1 클래스와메소드심층연구 ( 실습 ) 손시운 ssw5176@kangwon.ac.kr 예제 1. 접근제어 class A { private int a; int b; public int c; // 전용 // 디폴트 // 공용 public class Test { public static void main(string args[]) { A obj = new

More information

<4D F736F F F696E74202D20C1A63233C0E520B1D7B7A1C7C820C7C1B7CEB1D7B7A1B9D628B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

<4D F736F F F696E74202D20C1A63233C0E520B1D7B7A1C7C820C7C1B7CEB1D7B7A1B9D628B0ADC0C729205BC8A3C8AF20B8F0B5E55D> Power Java 제 23 장그래픽프로그래밍 이번장에서학습할내용 자바에서의그래픽 기초사항 기초도형그리기 색상 폰트 Java 2D Java 2D를이용한그리기 Java 2D 를이용한채우기 도형회전과평행이동 자바를이용하여서화면에그림을그려봅시다. 자바그래픽데모 자바그래픽의두가지방법 자바그래픽 AWT Java 2D AWT를사용하면기본적인도형들을쉽게그릴수있다. 어디서나잘실행된다.

More information

<4D F736F F F696E74202D20C1A63139C0E520B9E8C4A120B0FCB8AEC0DA28B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

<4D F736F F F696E74202D20C1A63139C0E520B9E8C4A120B0FCB8AEC0DA28B0ADC0C729205BC8A3C8AF20B8F0B5E55D> Power Java 제 19 장배치관리자 이번장에서학습할내용 배치관리자의개요 배치관리자의사용 FlowLayout BorderLayout GridLayout BoxLayout CardLayout 절대위치로배치 컨테이너안에서컴포넌트를배치하는방법에대하여살펴봅시다. 배치관리자 (layout manager) 컨테이너안의각컴포넌트의위치와크기를결정하는작업 [3/70] 상당히다르게보인다.

More information

<4D F736F F F696E74202D20C1A63038C0E520C5ACB7A1BDBABFCD20B0B4C3BC4928B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

<4D F736F F F696E74202D20C1A63038C0E520C5ACB7A1BDBABFCD20B0B4C3BC4928B0ADC0C729205BC8A3C8AF20B8F0B5E55D> Power Java 제 8 장클래스와객체 I 이번장에서학습할내용 클래스와객체 객체의일생직접 메소드클래스를 필드작성해 UML 봅시다. QUIZ 1. 객체는 속성과 동작을가지고있다. 2. 자동차가객체라면클래스는 설계도이다. 먼저앞장에서학습한클래스와객체의개념을복습해봅시다. 클래스의구성 클래스 (class) 는객체의설계도라할수있다. 클래스는필드와메소드로이루어진다.

More information

쉽게 풀어쓴 C 프로그래밍

쉽게 풀어쓴 C 프로그래밍 Power Java 제 11 장상속 이번장에서학습할내용 상속이란? 상속의사용 메소드재정의 접근지정자 상속과생성자 Object 클래스 종단클래스 상속을코드를재사용하기위한중요한기법입니다. 상속이란? 상속의개념은현실세계에도존재한다. 상속의장점 상속의장점 상속을통하여기존클래스의필드와메소드를재사용 기존클래스의일부변경도가능 상속을이용하게되면복잡한 GUI 프로그램을순식간에작성

More information

PowerPoint Presentation

PowerPoint Presentation Class - Property Jo, Heeseung 목차 section 1 클래스의일반구조 section 2 클래스선언 section 3 객체의생성 section 4 멤버변수 4-1 객체변수 4-2 클래스변수 4-3 종단 (final) 변수 4-4 멤버변수접근방법 section 5 멤버변수접근한정자 5-1 public 5-2 private 5-3 한정자없음

More information

쉽게 풀어쓴 C 프로그래밍

쉽게 풀어쓴 C 프로그래밍 Power Java 제 9 장생성자와접근제어 이번장에서학습할내용 생성자 정적변수 정적메소드 접근제어 this 클래스간의관계 객체가생성될때초기화를담당하는생성자에대하여살펴봅니다. 생성자 생성자 (contructor): 객체가생성될때에필드에게초기값을제공하고필요한초기화절차를실행하는메소드 생성자의예 class Car { private String color; // 색상

More information

5장.key

5장.key JAVA Programming 1 (inheritance) 2!,!! 4 3 4!!!! 5 public class Person {... public class Student extends Person { // Person Student... public class StudentWorker extends Student { // Student StudentWorker...!

More information

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

gnu-lee-oop-kor-lec10-1-chap10 어서와 Java 는처음이지! 제 10 장이벤트처리 이벤트분류 액션이벤트 키이벤트 마우스이동이벤트 어댑터클래스 스윙컴포넌트에의하여지원되는이벤트는크게두가지의카테고리로나누어진다. 사용자가버튼을클릭하는경우 사용자가메뉴항목을선택하는경우 사용자가텍스트필드에서엔터키를누르는경우 두개의버튼을만들어서패널의배경색을변경하는프로그램을작성하여보자. 이벤트리스너는하나만생성한다. class

More information

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

JAVA 프로그래밍실습 실습 1) 실습목표 - 메소드개념이해하기 - 매개변수이해하기 - 새메소드만들기 - Math 클래스의기존메소드이용하기 (   ) 문제 - 직사각형모양의땅이있다. 이땅의둘레, 면적과대각 JAVA 프로그래밍실습 실습 1) 실습목표 - 메소드개념이해하기 - 매개변수이해하기 - 새메소드만들기 - Math 클래스의기존메소드이용하기 ( http://java.sun.com/javase/6/docs/api ) 문제 - 직사각형모양의땅이있다. 이땅의둘레, 면적과대각선의길이를계산하는메소드들을작성하라. 직사각형의가로와세로의길이는주어진다. 대각선의길이는 Math클래스의적절한메소드를이용하여구하라.

More information

PowerPoint Presentation

PowerPoint Presentation public class SumTest { public static void main(string a1[]) { int a, b, sum; a = Integer.parseInt(a1[0]); b = Integer.parseInt(a1[1]); sum = a + b ; // 두수를더하는부분입니다 System.out.println(" 두수의합은 " + sum +

More information

PowerPoint Presentation

PowerPoint Presentation 객체지향프로그래밍 상속 손시운 ssw5176@kangwon.ac.kr 상속이란? 상속의개념은현실세계에도존재한다. 2 상속의장점 상속의장점 상속을통하여기존클래스의필드와메소드를재사용 기존클래스의일부변경도가능 상속을이용하게되면복잡한 GUI 프로그램을순식간에작성 상속은이미작성된검증된소프트웨어를재사용 신뢰성있는소프트웨어를손쉽게개발, 유지보수 코드의중복을줄일수있다. 3

More information

PowerPoint Presentation

PowerPoint Presentation 자바프로그래밍 1 배열 손시운 ssw5176@kangwon.ac.kr 배열이필요한이유 예를들어서학생이 10 명이있고성적의평균을계산한다고가정하자. 학생 이 10 명이므로 10 개의변수가필요하다. int s0, s1, s2, s3, s4, s5, s6, s7, s8, s9; 하지만만약학생이 100 명이라면어떻게해야하는가? int s0, s1, s2, s3, s4,

More information

Microsoft PowerPoint - 2강

Microsoft PowerPoint - 2강 컴퓨터과학과 김희천교수 학습개요 Java 언어문법의기본사항, 자료형, 변수와상수선언및사용법, 각종연산자사용법, if/switch 등과같은제어문사용법등에대해설명한다. 또한 C++ 언어와선언 / 사용방법이다른 Java의배열선언및사용법에대해서설명한다. Java 언어의효과적인활용을위해서는기본문법을이해하는것이중요하다. 객체지향의기본개념에대해알아보고 Java에서어떻게객체지향적요소를적용하고있는지살펴본다.

More information

<4D F736F F F696E74202D20C1A63138C0E520C0CCBAA5C6AE20C3B3B8AE28B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

<4D F736F F F696E74202D20C1A63138C0E520C0CCBAA5C6AE20C3B3B8AE28B0ADC0C729205BC8A3C8AF20B8F0B5E55D> Power Java 제 18 장이벤트처리 이번장에서학습할내용 이벤트처리의개요 이벤트 액션이벤트 Key, Mouse, MouseMotion 어댑터클래스 버튼을누르면반응하도록만들어봅시다. 이번장의목표 버튼을누르면버튼의텍스트가변경되게한다. 이벤트처리과정 이벤트처리과정 (1) 이벤트를발생하는컴포넌트를생성하여야한다. 이벤트처리과정 (2) 이벤트리스너클래스를작성한다.

More information

쉽게 풀어쓴 C 프로그래밍

쉽게 풀어쓴 C 프로그래밍 제 11 장상속 1. 상속의개념을이해한다. 2. 상속을이용하여자식클래스를작성할수있다. 3. 상속과접근지정자와의관계를이해한다. 4. 상속시생성자와소멸자가호출되는순서를이해한다. 이번장에서만들어볼프로그램 class Circle { int x, y; int radius;... class Rect { int x, y; int width, height;... 중복 상속의개요

More information

Microsoft PowerPoint - 14주차 강의자료

Microsoft PowerPoint - 14주차 강의자료 Java 로만드는 Monster 잡기게임예제이해 2014. 12. 2 게임화면및게임방법 기사초기위치 : (0,0) 아이템 10 개랜덤생성 몬스터 10 놈랜덤생성 Frame 하단에기사위치와기사파워출력방향키로기사이동아이템과몬스터는고정종료버튼클릭하면종료 Project 구성 GameMain.java GUI 환경설정, Main Method 게임객체램덤위치에생성 Event

More information

PowerPoint Presentation

PowerPoint Presentation 객체지향프로그래밍 클래스와메소드심층연구 손시운 ssw5176@kangwon.ac.kr 접근제어 클래스안에변수나메소드들을누구나사용할수있게하면어떻게될까? 많은문제가발생할것이다. ( 예 ) 국가기밀서류를누구나보도록방치하면어떻게될까? 2 접근제어 접근제어 (access control): 다른클래스가특정한필드나메소드에접근하는 것을제어하는것 3 멤버수준에서의접근제어 4

More information

Microsoft PowerPoint - 04-UDP Programming.ppt

Microsoft PowerPoint - 04-UDP Programming.ppt Chapter 4. UDP Dongwon Jeong djeong@kunsan.ac.kr http://ist.kunsan.ac.kr/ Dept. of Informatics & Statistics 목차 UDP 1 1 UDP 개념 자바 UDP 프로그램작성 클라이언트와서버모두 DatagramSocket 클래스로생성 상호간통신은 DatagramPacket 클래스를이용하여

More information

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

제8장 자바 GUI 프로그래밍 II 제8장 MVC Model 8.1 MVC 모델 (1/7) MVC (Model, View, Controller) 모델 스윙은 MVC 모델에기초를두고있다. MVC란 Xerox의연구소에서 Smalltalk 언어를바탕으로사용자인터페이스를개발하기위한방법 MVC는 3개의구성요소로구성 Model : 응용프로그램의자료를표현하기위한모델 View : 자료를시각적으로 (GUI 방식으로

More information

<4D F736F F F696E74202D20C1A63230C0E520BDBAC0AE20C4C4C6F7B3CDC6AE203128B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

<4D F736F F F696E74202D20C1A63230C0E520BDBAC0AE20C4C4C6F7B3CDC6AE203128B0ADC0C729205BC8A3C8AF20B8F0B5E55D> Power Java 제 20 장스윙컴포넌트 1 이번장에서학습할내용 텍스트컴포넌트 텍스트필드 텍스트영역 스크롤페인 체크박스 라디오버튼 스윙에서제공하는기초적인컴포넌트들을살펴봅시다. 스윙텍스트컴포넌트들 종류텍스트컴포넌트그림 텍스트필드 JTextField JPasswordField JFormattedTextField 일반텍스트영역 JTextArea 스타일텍스트영역

More information

Java Programing Environment

Java Programing Environment Lab Exercise #7 Swing Component 프로그래밍 2007 봄학기 고급프로그래밍 김영국충남대전기정보통신공학부 실습내용 실습과제 7-1 : 정규표현식을이용한사용자정보의유효성검사 (ATM 에서사용자등록용도로사용가능 ) 실습과제 7-2 : 숫자맞추기게임 실습과제 7-3 : 은행관리프로그램 고급프로그래밍 Swing Component 프로그래밍 2

More information

PowerPoint Presentation

PowerPoint Presentation 객체지향프로그래밍 인터페이스, 람다식, 패키지 손시운 ssw5176@kangwon.ac.kr 인터페이스 인터페이스 (interafce) 는서로다른장치들이연결되어서상호데이터를주 고받는규격을의미한다 2 자바인터페이스 클래스와클래스사이의상호작용의규격을나타낸것이인터페이스이다 3 인터페이스의예 스마트홈시스템 (Smart Home System) 4 인터페이스의정의 public

More information

쉽게 풀어쓴 C 프로그래밍

쉽게 풀어쓴 C 프로그래밍 클래스와객체 I 이번시간에서학습할내용 클래스와객체 객체의일생 메소드 필드 UML 직접클래스를작성해봅시다. 클래스의구성 클래스 (class) 는객체의설계도라할수있다. 클래스는필드와메소드로이루어진다. 필드 (field) 는객체의속성을나타낸다. 메소드 (method) 는객체의동작을나타낸다. 클래스정의의예 class Car { // 필드정의 public int speed;

More information

PowerPoint Presentation

PowerPoint Presentation 객체지향프로그래밍 클래스, 객체, 메소드 손시운 ssw5176@kangwon.ac.kr 실제세계는객체로이루어진다. 2 객체와메시지 3 객체지향이란? 실제세계를모델링하여소프트웨어를개발하는방법 4 객체 5 객체란? 객체 (Object) 는상태와동작을가지고있다. 객체의상태 (state) 는객체의특징값 ( 속성 ) 이다. 객체의동작 (behavior) 또는행동은객체가취할수있는동작

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 Lab 4 ADT Design 클래스로정의됨. 모든객체들은힙영역에할당됨. 캡슐화 (Encapsulation) : Data representation + Operation 정보은닉 (Information Hiding) : Opertion부분은가려져있고, 사용자가 operation으로만사용가능해야함. 클래스정의의형태 public class Person { private

More information

9장.key

9장.key JAVA Programming 1 GUI(Graphical User Interface) 2 GUI!,! GUI! GUI, GUI GUI! GUI AWT Swing AWT - java.awt Swing - javax.swing AWT Swing 3 AWT(Abstract Windowing Toolkit)! GUI! java.awt! AWT (Heavy weight

More information

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

Microsoft Word - java18-1-final-answer.doc 기말고사 담당교수 : 단국대학교응용컴퓨터공학박경신 답은반드시답안지에기술할것. 공간이부족할경우반드시답안지몇쪽의뒤에있다고명기한후기술할것. 그외의경우의답안지뒤쪽이나연습지에기술한내용은답안으로인정안함. 답에는반드시네모를쳐서확실히표시할것. 답안지에학과, 학번, 이름외에본인의암호 (4자리숫자 ) 를기입하면성적공고시학번대신암호를사용할것임. 1. 다음 sub1 과 sub2

More information

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

자바GUI실전프로그래밍2_장대원.PDF JAVA GUI - 2 JSTORM http://wwwjstormpekr JAVA GUI - 2 Issued by: < > Document Information Document title: JAVA GUI - 2 Document file name: Revision number: Issued by: Issue Date:

More information

01-OOPConcepts(2).PDF

01-OOPConcepts(2).PDF Object-Oriented Programming Concepts Tel: 02-824-5768 E-mail: hhcho@selabsoongsilackr? OOP (Object) (Encapsulation) (Message) (Class) (Inheritance) (Polymorphism) (Abstract Class) (Interface) 2 1 + = (Dependency)

More information

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

q 이장에서다룰내용 1 객체지향프로그래밍의이해 2 객체지향언어 : 자바 2 객체지향프로그래밍 IT CookBook, 자바로배우는쉬운자료구조 q 이장에서다룰내용 1 객체지향프로그래밍의이해 2 객체지향언어 : 자바 2 q 객체지향프로그래밍의이해 v 프로그래밍기법의발달 A 군의사업발전 1 단계 구조적프로그래밍방식 3 q 객체지향프로그래밍의이해 A 군의사업발전 2 단계 객체지향프로그래밍방식 4 q 객체지향프로그래밍의이해 v 객체란무엇인가

More information

쉽게 풀어쓴 C 프로그래밍

쉽게 풀어쓴 C 프로그래밍 제 5 장생성자와접근제어 1. 객체지향기법을이해한다. 2. 클래스를작성할수있다. 3. 클래스에서객체를생성할수있다. 4. 생성자를이용하여객체를초기화할수 있다. 5. 접근자와설정자를사용할수있다. 이번장에서만들어볼프로그램 생성자 생성자 (constructor) 는초기화를담당하는함수 생성자가필요한이유 #include using namespace

More information

<4D F736F F F696E74202D20C1A63236C0E520BED6C7C3B8B428B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

<4D F736F F F696E74202D20C1A63236C0E520BED6C7C3B8B428B0ADC0C729205BC8A3C8AF20B8F0B5E55D> Power Java 제 26 장애플릿 이번장에서학습할내용 애플릿소개 애플릿작성및소개 애플릿의생명주기 애플릿에서의그래픽컴포넌트의소개 Applet API의이용 웹브라우저상에서실행되는작은프로그램인애플릿에대하여학습합니다. 애플릿이란? 애플릿은웹페이지같은 HTML 문서안에내장되어실행되는자바프로그램이다. 애플릿을실행시키는두가지방법 1. 웹브라우저를이용하는방법 2. Appletviewer를이용하는방법

More information

ch09

ch09 9 Chapter CHAPTER GOALS B I G J A V A 436 CHAPTER CONTENTS 9.1 436 Syntax 9.1 441 Syntax 9.2 442 Common Error 9.1 442 9.2 443 Syntax 9.3 445 Advanced Topic 9.1 445 9.3 446 9.4 448 Syntax 9.4 454 Advanced

More information

JAVA PROGRAMMING 실습 05. 객체의 활용

JAVA PROGRAMMING 실습 05. 객체의 활용 public class Person{ public String name; public int age; } public Person(){ } public Person(String s, int a){ name = s; age = a; } public String getname(){ return name; } @ 객체의선언 public static void main(string

More information

Microsoft PowerPoint - Java7.pptx

Microsoft PowerPoint - Java7.pptx HPC & OT Lab. 1 HPC & OT Lab. 2 실습 7 주차 Jin-Ho, Jang M.S. Hanyang Univ. HPC&OT Lab. jinhoyo@nate.com HPC & OT Lab. 3 Component Structure 객체 (object) 생성개념을이해한다. 외부클래스에대한접근방법을이해한다. 접근제어자 (public & private)

More information

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

Microsoft PowerPoint - ÀÚ¹Ù08Àå-1.ppt AWT 컴포넌트 (1) 1. AWT 패키지 2. AWT 프로그램과이벤트 3. Component 클래스 4. 컴포넌트색칠하기 AWT GUI 를만들기위한 API 윈도우프로그래밍을위한클래스와도구를포함 Graphical User Interface 그래픽요소를통해프로그램과대화하는방식 그래픽요소를 GUI 컴포넌트라함 윈도우프로그램만들기 간단한 AWT 프로그램 import

More information

제11장 프로세스와 쓰레드

제11장 프로세스와 쓰레드 제9장자바쓰레드 9.1 Thread 기초 (1/5) 프로그램 명령어들의연속 (a sequence of instruction) 프로세스 / Thread 실행중인프로그램 (program in execution) 프로세스생성과실행을위한함수들 자바 Thread 2 9.1 Thread 기초 (2/5) 프로세스단위작업의문제점 프로세스생성시오버헤드 컨텍스트스위치오버헤드

More information

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

Microsoft PowerPoint - java1-lecture6.ppt [호환 모드] 실세계의인터페이스와인터페이스의필요성 인터페이스, 람다식 514760-1 2017 년가을학기 10/2/2017 박경신 정해진규격 ( 인터페이스 ) 에맞기만하면연결가능. 각회사마다구현방법은다름 정해진규격 ( 인터페이스 ) 에맞지않으면연결불가 인터페이스의필요성 인터페이스를이용하여다중상속구현 자바에서클래스다중상속불가 인터페이스는명세서와같음 인터페이스만선언하고구현을분리하여,

More information

Design Issues

Design Issues 11 COMPUTER PROGRAMMING INHERIATANCE CONTENTS OVERVIEW OF INHERITANCE INHERITANCE OF MEMBER VARIABLE RESERVED WORD SUPER METHOD INHERITANCE and OVERRIDING INHERITANCE and CONSTRUCTOR 2 Overview of Inheritance

More information

PowerPoint Presentation

PowerPoint Presentation 객체지향프로그래밍 그래픽사용자인터페이스 손시운 ssw5176@kangwon.ac.kr 그래픽사용자인터페이스 그래픽사용자인터페이스 (Graphical User Interface, 간단히 GUI) 는컴포넌 트들로구성된다. 2 자바에서 GUI 의종류 GUI AWT(Abstract Windows Toolkit) AWT 는운영체제가제공하는자원을이용하여서컴포넌트를생성

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 인터페이스 배효철 th1g@nate.com 1 목차 인터페이스의역할 인터페이스선언 인터페이스구현 인터페이스사용 타입변환과다형성 인터페이스상속 디폴트메소드와인터페이스확장 2 인터페이스의역할 인터페이스란? 개발코드와객체가서로통신하는접점 개발코드는인터페이스의메소드만알고있으면 OK 인터페이스의역할 개발코드가객체에종속되지않게 -> 객체교체할수있도록하는역할 개발코드변경없이리턴값또는실행내용이다양해질수있음

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 실습 1 배효철 th1g@nate.com 1 목차 조건문 반복문 System.out 구구단 모양만들기 Up & Down 2 조건문 조건문의종류 If, switch If 문 조건식결과따라중괄호 { 블록을실행할지여부결정할때사용 조건식 true 또는 false값을산출할수있는연산식 boolean 변수 조건식이 true이면블록실행하고 false 이면블록실행하지않음 3

More information

쉽게 풀어쓴 C 프로그래밍

쉽게 풀어쓴 C 프로그래밍 객체지향프로그래밍 (OOP: object-oriented programming) 은우리가살고있는실제세계가객체 (object) 들로구성되어있는것과비슷하게, 소프트웨어도객체로구성하는방법이다. 객체는상태와동작을가지고있다. 객체의상태 (state) 는객체의속성이다. 객체의동작 (behavior) 은객체가취할수있는동작 ( 기능 ) 이다. 객체에대한설계도를클래스 (class)

More information

PowerPoint Presentation

PowerPoint Presentation Package Class 1 Heeseung Jo 목차 section 1 패키지개요와패키지의사용 section 2 java.lang 패키지의개요 section 3 Object 클래스 section 4 포장 (Wrapper) 클래스 section 5 문자열의개요 section 6 String 클래스 section 7 StringBuffer 클래스 section

More information

No Slide Title

No Slide Title 상속 이충기 명지대학교컴퓨터공학과 상속 Q: 건설회사는기존아파트와조금다르거나추가적인특징들을가진새아파트를지을때어떻게하는가? A: 2 상속 상속 (inheritance) 은클래스들을연관시키는자연스럽고계층적인방법이다. 상속은객체지향프로그래밍의가장중요한개념중의하나이다. 상속은 은 이다 라는관계 (is-a relationship) 를나타낸다. 이관계를적용하여클래스들을상하관계로연결하는것이상속이다.

More information

쉽게 풀어쓴 C 프로그래밊

쉽게 풀어쓴 C 프로그래밊 C++ Exspresso 제 5 장클래스의기초 이번장에서학습할내용 클래스와객체 객체의일생 메소드 필드 UML 직접클래스를작성해봅시다. QUIZ 1. 객체는 속성과 동작을가지고있다. 2. 자동차가객체라면클래스는 설계도이다. 먼저앞장에서학습한클래스와객체의개념을복습해봅시다. 1. 클래스의구성 클래스 (class) 는객체의설계도라할수있다. 클래스는멤버변수와멤버함수로이루어진다.

More information

쉽게 풀어쓴 C 프로그래밍

쉽게 풀어쓴 C 프로그래밍 Power Java 제 7 장클래스와객체 이번장에서학습할내용 객체지향이란? 객체 메시지 클래스 객체지향의장점 String 클래스 객체지향개념을완벽하게이해해야만객체지향설계의이점을활용할수있다. 실제세계는객체로이루어진다. 객체지향이란? 실제세계를모델링하여소프트웨어를개발하는방법 절차지향과객체지향 절차지향프로그래밍 (procedural programming): 문제를해결하는절차를중요하게생각하는방법

More information

슬라이드 1

슬라이드 1 UNIT 12 상속과오버라이딩 로봇 SW 교육원 2 기 최상훈 학습목표 2 클래스를상속핛수있다. 메소드오버라이딩을사용핛수있다. 패키지선언과 import 문을사용핛수있다. 상속 (inheritance) 3 상속이란 기존의클래스를기반으로새로운클래스를작성 두클래스를부모와자식으로관계를맺어주는것 자식은부모의모든멤버를상속받음 연관된일렦의클래스에대핚공통적인규약을정의 class

More information

JAVA PROGRAMMING 실습 09. 예외처리

JAVA PROGRAMMING 실습 09. 예외처리 2015 학년도 2 학기 예외? 프로그램실행중에발생하는예기치않은사건 예외가발생하는경우 정수를 0으로나누는경우 배열의크기보다큰인덱스로배열의원소를접근하는경우 파일의마지막부분에서데이터를읽으려고하는경우 예외처리 프로그램에문제를발생시키지않고프로그램을실행할수있게적절한조치를취하는것 자바는예외처리기를이용하여예외처리를할수있는기법제공 자바는예외를객체로취급!! 나뉨수를입력하시오

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 @ Lesson 2... ( ). ( ). @ vs. logic data method variable behavior attribute method field Flow (Type), ( ) member @ () : C program Method A ( ) Method B ( ) Method C () program : Java, C++, C# data @ Program

More information

05-class.key

05-class.key 5 : 2 (method) (public) (private) (interface) 5.1 (Method), (public method) (private method) (constructor), 3 4 5.2 (client). (receiver)., System.out.println("Hello"); (client object) (receiver object)

More information

PowerPoint Presentation

PowerPoint Presentation Package Class 3 Heeseung Jo 목차 section 1 패키지개요와패키지의사용 section 2 java.lang 패키지의개요 section 3 Object 클래스 section 4 포장 (Wrapper) 클래스 section 5 문자열의개요 section 6 String 클래스 section 7 StringBuffer 클래스 section

More information

쉽게

쉽게 Power Java 제 4 장자바프로그래밍기초 이번장에서학습할내용 자바프로그램에대한기초사항을학습 자세한내용들은추후에. Hello.java 프로그램 주석 주석 (comment): 프로그램에대한설명을적어넣은것 3 가지타입의주석 클래스 클래스 (class): 객체를만드는설계도 ( 추후에학습 ) 자바프로그램은클래스들로구성된다. 그림 4-1. 자바프로그램의구조 클래스정의

More information

11장.key

11장.key JAVA Programming 1 GUI 2 2 1. GUI! GUI! GUI.! GUI! GUI 2. GUI!,,,!! GUI! GUI 11 : GUI 12 : GUI 3 4, JComponent 11-1 :, JComponent 5 import java.awt.*; import java.awt.event.*; import javax.swing.*; public

More information

09-interface.key

09-interface.key 9 Database insert(record r): boolean find(key k): Record 1 Record getkey(): Key * Record Key Database.? Key equals(key y): boolean Database insert(record r): boolean find(key k): Record * Database OK 1

More information

강의자료

강의자료 Copyright, 2014 MMLab, Dept. of ECE, UOS Java Swing 2014 년 3 월 최성종서울시립대학교전자전기컴퓨터공학부 chois@uos.ac.kr http://www.mmlab.net 차례 2014년 3월 Java Swing 2 2017-06-02 Seong Jong Choi Java Basic Concepts-3 Graphical

More information

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

Microsoft PowerPoint 자바-기본문법(Ch2).pptx 자바기본문법 1. 기본사항 2. 자료형 3. 변수와상수 4. 연산자 1 주석 (Comments) 이해를돕기위한설명문 종류 // /* */ /** */ 활용예 javadoc HelloApplication.java 2 주석 (Comments) /* File name: HelloApplication.java Created by: Jung Created on: March

More information

No Slide Title

No Slide Title 클래스와객체 이충기 명지대학교컴퓨터공학과 들어가며 Q: 축구게임에서먼저공격하는팀을정하기위해동전을던진다. 우리는동전을던질때앞면이나오느냐아니면뒷면이나오느냐에만관심이있다. 또한동전을가지고해야할일은동전을던지는것과동전을던진후결과를알면된다. 이동전을효과적으로나타낼수있는방법을기술하라. A: 2 클래스와객체 객체 (object): 우리주변의어떤대상의모델이다. - 예 : 학생,

More information

TEST BANK & SOLUTION

TEST BANK & SOLUTION TEST BANK & SOLUTION 어서와자바는처음이지!" 를강의교재로채택해주셔서감사드립니다. 본문제집을만드는데나름대로노력을기울였으나제가가진지식의한계로말미암아잘못된부분이있을것으로사료됩니다. 잘못된부분을발견하시면 chunik@sch.ac.kr로연락주시면더좋은책을만드는데소중하게사용하겠습니다. 다시한번감사드립니다. 1. 자바언어에서지원되는 8 가지의기초자료형은무엇인가?

More information

PowerPoint Presentation

PowerPoint Presentation public class SumTest { public static void main(string a1[]) { int a, b, sum; a = Integer.parseInt(a1[0]); b = Integer.parseInt(a1[1]); sum = a + b ; // 두수를더하는부분입니다 System.out.println(" 두수의합은 " + sum +

More information

JAVA PROGRAMMING 실습 02. 표준 입출력

JAVA PROGRAMMING 실습 02. 표준 입출력 # 왜생겼나요..? : 절차지향언어가가진단점을보완하고다음의목적을달성하기위해..! 1. 소프트웨어생산성향상 객체지향소프트웨어를새로만드는경우이미만든개체지향소프트웨어를상속받거나객체를 가져다재사용할수있어부분수정을통해소프트웨어를다시만드는부담줄임. 2. 실세계에대한쉬운모델링 실세계의일은절차나과정보다는일과관련된많은물체들의상호작용으로묘사. 캡슐화 메소드와데이터를클래스내에선언하고구현

More information

Microsoft PowerPoint 장강의노트.ppt

Microsoft PowerPoint 장강의노트.ppt 클래스와객체 클래스와객체 객체 : 우리주변의어떤대상의모델 - 예 : 사람, 차, TV, 개 객체 = 상태 (state) + 행동 (behavior) - 예 : 개의상태 - 종자, 이름, 색개의행동 - 짖다, 가져오다 상태는변수로행동은메소드로나타냄 객체는클래스에의해정의된다. 클래스는객체가생성되는틀혹은청사진이다. 2 예 : 클래스와객체 질문 : 클래스와객체의다른예는?

More information

예제 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

예제 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 제 10 장상속 예제 1) ConstructorTest.java class Parent public Parent() super - default"); public Parent(int i) this("hello"); super(int) constructor" + i); public Parent(char c) this(); super(char) constructor

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 예외처리 배효철 th1g@nate.com 1 목차 예외와예외클래스 실행예외 예외처리코드 예외종류에따른처리코드 자동리소스닫기 예외처리떠넘기기 사용자정의예외와예외발생 예외와예외클래스 구문오류 예외와예외클래스 구문오류가없는데실행시오류가발생하는경우 예외와예외클래스 import java.util.scanner; public class ExceptionExample1

More information

JAVA PROGRAMMING 실습 07. 상속

JAVA PROGRAMMING 실습 07. 상속 상속 부모클래스에정의된필드와메소드를자식클래스가물려받는것 슈퍼클래스 (superclass) 특성을물려주는상위클래스 서브클래스 (subclass) 특성을물려받는하위클래스 슈퍼클래스에자신만의특성 ( 필드, 메소드 ) 추가 슈퍼클래스의특성 ( 메소드 ) 을수정 = 오버라이딩구체화 class Phone 전화걸기전화받기 class MobilePhone 전화걸기전화받기무선기지국연결배터리충전하기

More information

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

(Microsoft PowerPoint - java1-lecture11.ppt [\310\243\310\257 \270\360\265\345]) 예외와예외클래스 예외처리 514760-1 2016 년가을학기 12/08/2016 박경신 오류의종류 에러 (Error) 하드웨어의잘못된동작또는고장으로인한오류 에러가발생되면 JVM실행에문제가있으므로프로그램종료 정상실행상태로돌아갈수없음 예외 (Exception) 사용자의잘못된조작또는개발자의잘못된코딩으로인한오류 예외가발생되면프로그램종료 예외처리 추가하면정상실행상태로돌아갈수있음

More information

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

Microsoft Word - java19-1-final-answer.doc 기말고사 담당교수 : 단국대학교응용컴퓨터공학박경신 답은반드시답안지에기술할것. 공간이부족할경우반드시답안지몇쪽의뒤에있다고명기한후기술할것. 그외의경우의답안지뒤쪽이나연습지에기술한내용은답안으로인정안함. 답에는반드시네모를쳐서확실히표시할것. 답안지에학과, 학번, 이름외에본인의암호 (4자리숫자 ) 를기입하면성적공고시학번대신암호를 사용할것임. 1. 다음코드의실행결과를적어라

More information

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µå

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µå 기초통계프로그래밍 클래스, 객체, 변수, 메소드 hmkang@hallym.ac.kr 금융정보통계학과 강희모 ( 금융정보통계학과 ) 기초통계프로그래밍 1 / 26 자바구성파일 소스파일 소스파일 : 사용자가직접에디터에입력하는파일로자바프로그램언어가제공하는형식으로제작 소스파일의확장자는.java 임 컴파일 : javac 명령어를이용하여프로그래머가만든소스파일을컴파일하여실행파일.class

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 System Software Experiment 1 Lecture 5 - Array Spring 2019 Hwansoo Han (hhan@skku.edu) Advanced Research on Compilers and Systems, ARCS LAB Sungkyunkwan University http://arcs.skku.edu/ 1 배열 (Array) 동일한타입의데이터가여러개저장되어있는저장장소

More information

Microsoft PowerPoint - java1-lab5-ImageProcessorTestOOP.pptx

Microsoft PowerPoint - java1-lab5-ImageProcessorTestOOP.pptx 2018 학년도 1 학기 JAVA 프로그래밍 II 514760-1 2018 년봄학기 5/10/2018 박경신 Lab#1 (ImageTest) Lab#1 은영상파일 (Image) 을읽어서정보를출력 Java Tutorials Lesson: Working with Images https://docs.oracle.com/javase/tutorial/2d/images/index.html

More information

<322EBCF8C8AF28BFACBDC0B9AEC1A6292E687770>

<322EBCF8C8AF28BFACBDC0B9AEC1A6292E687770> 연습문제해답 5 4 3 2 1 0 함수의반환값 =15 5 4 3 2 1 0 함수의반환값 =95 10 7 4 1-2 함수의반환값 =3 1 2 3 4 5 연습문제해답 1. C 언어에서의배열에대하여다음중맞는것은? (1) 3차원이상의배열은불가능하다. (2) 배열의이름은포인터와같은역할을한다. (3) 배열의인덱스는 1에서부터시작한다. (4) 선언한다음, 실행도중에배열의크기를변경하는것이가능하다.

More information

PowerPoint Presentation

PowerPoint Presentation 객체지향프로그래밍 이벤트처리 손시운 ssw5176@kangwon.ac.kr 이벤트 - 구동프로그래밍 이벤트 - 구동프로그래밍 (event-driven programming): 프로그램의실행이이벤트의발생에의하여결정되는방식 2 이벤트처리과정 3 이벤트리스너 발생된이벤트객체에반응하여서이벤트를처리하는객체를이벤트리스너 (event listener) 라고한다. 4 이벤트처리과정

More information

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

(Microsoft PowerPoint - java2-lecture3.ppt [\310\243\310\257 \270\360\265\345]) Class Class, Collections 514770-1 2017 년봄학기 3/22/2017 박경신 클래스 (Class) 객체의속성과행위선언 객체의설계도혹은틀 객체 (Object) 클래스의틀로찍어낸실체 메모리공간을갖는구체적인실체 클래스를구체화한객체를인스턴스 (instance) 라고부름 객체와인스턴스는같은뜻으로사용 클래스구조 클래스접근권한, public 다른클래스들에서이클래스를사용하거나접근할수있음을선언

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 클래스 ( 계속 ) 배효철 th1g@nate.com 1 목차 인스턴스멤버와 this 객체의소멸과가비지 정적멤버와 static final 필드와상수 패키지 접근제한자 Getter와 Setter 2 목차 인스턴스멤버와 this 객체의소멸과가비지 정적멤버와 static final 필드와상수 패키지 접근제한자 Getter와 Setter 3 인스턴스멤버와 this 인스턴스멤버란?

More information

JAVA PROGRAMMING 실습 05. 객체의 활용

JAVA PROGRAMMING 실습 05. 객체의 활용 2015 학년도 2 학기 public class Person{ public String name; public int age; public Person(){ public Person(String s, int a){ name = s; age = a; public String getname(){ return name; @ 객체의선언 public static void

More information

No Slide Title

No Slide Title 그래픽사용자인터페이스 이충기 명지대학교컴퓨터공학과 그래픽사용자인터페이스 그래픽사용자인터페이스 (GUI) 는사람과컴퓨터간의상호작용을위한사람 - 컴퓨터인터페이스 (HCI) 중의하나이다. GUI 는사용자가컴퓨터화면상에있는객체들과상호작용을하는인터페이스이다. 오늘날사실상거의모든컴퓨터플랫폼에서 GUI 가사용되고있다. 2 GUI 프로그래밍 GUI 프로그램은실행시키면메뉴가있는창이뜨고창에는아이콘,

More information

PowerPoint Template

PowerPoint Template 7. 상속 (inheritance) 의이해 상속의기본개념 상속의생성자, 소멸자 protected 멤버 Jong Hyuk Park 상속의기본개념 Jong Hyuk Park 상속의기본개념 상속의예 1 " 철수는아버지로부터좋은목소리와큰키를물려받았다." 상속의예 2 "Student 클래스가 Person 클래스를상속한다." 아버지 Person 철수 Stduent 3

More information

PowerPoint Presentation

PowerPoint Presentation Class : Method Jo, Heeseung 목차 section 1 생성자 (Constructor) section 2 생성자오버로딩 (Overloading) section 3 예약어 this section 4 메소드 4-1 접근한정자 4-2 클래스메소드 4-3 final, abstract, synchronized 메소드 4-4 메소드반환값 (return

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 상속 배효철 th1g@nate.com 1 목차 상속개념 클래스상속 부모생성자호출 메소드재정의 final 클래스와 final 메소드 protected 접근제한자 타입변환과다형성 추상클래스 2 상속개념 상속 (Inheritance) 이란? 현실세계 : 부모가자식에게물려주는행위 부모가자식을선택해서물려줌 객체지향프로그램 : 자식 ( 하위, 파생 ) 클래스가부모 (

More information

Modern Javascript

Modern Javascript ES6 - Arrow Function Class Template String Destructuring Default, Rest, Spread let, const for..of Promises Module System Map, Set * Generator * Symbol * * https://babeljs.io/ Babel is a JavaScript compiler.

More information

8장.그래픽 프로그래밍

8장.그래픽 프로그래밍 윈도우프레임 도형그리기색과폰트이미지그리기그리기응용 2 윈도우프레임 제목표시줄을갖는윈도우를의미 생성과정 1 JFrame 객체생성 2 프레임의크기설정 3 프레임의제목설정 4 기본닫힘연산지정 5 프레임이보이도록만듦. 3 윈도우프레임예제 [ 예제 8.1 - EmptyFrameViewer.java] import javax.swing.*; public class EmptyFrameViewer

More information

10장.key

10장.key JAVA Programming 1 2 (Event Driven Programming)! :,,,! ( )! : (batch programming)!! ( : )!!!! 3 (Mouse Event, Action Event) (Mouse Event, Action Event) (Mouse Event, Container Event) (Key Event) (Key Event,

More information

쉽게 풀어쓴 C 프로그래밍

쉽게 풀어쓴 C 프로그래밍 Power Java 제 23 장스레드 이번장에서학습할내용 스레드의개요 스레드의생성과실행 스레드상태 스레드의스케줄링 스레드간의조정 스레드는동시에여러개의프로그램을실행하는효과를냅니다. 멀티태스킹 멀티태스킹 (muli-tasking) 는여러개의애플리케이션을동시에실행하여서컴퓨터시스템의성능을높이기위한기법 스레드란? 다중스레딩 (multi-threading) 은하나의프로그램이동시에여러가지작업을할수있도록하는것

More information

No Slide Title

No Slide Title 사건처리와 GUI 프로그래밍 이충기 명지대학교컴퓨터공학과 사건 사건은우리가관심을가질지모르는어떤일이일어나는것을나타내는객체이다. 예를들면, 다음이일어날때프로그램이어떤일을수행해야하는경우에사건이발생한다 : 1. 마우스를클릭한다. 2. 단추를누른다. 3. 키보드의키를누른다. 4. 메뉴항목을선택한다. 2 사건 사건은컴포넌트에서사용자나시스템에의하여발생하는일이다. 자바는사건을나타내는많은사건클래스를제공한다.

More information

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

Spring Data JPA Many To Many 양방향 관계 예제 Spring Data JPA Many To Many 양방향관계예제 오라클자바커뮤니티 (ojc.asia, ojcedu.com) 엔티티매핑 (Entity Mapping) M : N 연관관계 사원 (Sawon), 취미 (Hobby) 는다 : 다관계이다. 사원은여러취미를가질수있고, 하나의취미역시여러사원에할당될수있기때문이다. 보통관계형 DB 에서는다 : 다관계는 1

More information

설계란 무엇인가?

설계란 무엇인가? 금오공과대학교 C++ 프로그래밍 jhhwang@kumoh.ac.kr 컴퓨터공학과 황준하 9 강. 클래스의활용목차 멤버함수의외부정의 this 포인터 friend 선언 static 멤버 임시객체 1 /17 9 강. 클래스의활용멤버함수의외부정의 멤버함수정의구현방법 내부정의 : 클래스선언내에함수정의구현 외부정의 클래스선언 : 함수프로토타입 멤버함수정의 : 클래스선언외부에구현

More information

PowerPoint Presentation

PowerPoint Presentation 객체지향프로그래밍 그래픽프로그래밍 손시운 ssw5176@kangwon.ac.kr 자바에서의그래픽 2 자바그래픽의두가지방법 3 간단한예제 4 (1) 프레임생성하기 public class BasicPaint { public static void main(string[] args) { JFrame f = new JFrame(" 그래픽기초프로그램 "); f.setdefaultcloseoperation(jframe.exit_on_close);

More information

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

public class FlowLayoutPractice extends JFrame { public FlowLayoutPractice() { super(flowlayout Practice); this. Container contentpane = getcontentp 8 장 1 번 public class MyFrame extends JFrame { public MyFrame(String title) { super(title); this. setsize(400,200); new MyFrame("Let's study Java"); 2번 public class MyBorderLayoutFrame extends JFrame {

More information

PowerPoint Template

PowerPoint Template 16-1. 보조자료템플릿 (Template) 함수템플릿 클래스템플릿 Jong Hyuk Park 함수템플릿 Jong Hyuk Park 함수템플릿소개 함수템플릿 한번의함수정의로서로다른자료형에대해적용하는함수 예 int abs(int n) return n < 0? -n : n; double abs(double n) 함수 return n < 0? -n : n; //

More information

자바 프로그래밍

자바 프로그래밍 5 (kkman@mail.sangji.ac.kr) (Class), (template) (Object) public, final, abstract [modifier] class ClassName { // // (, ) Class Circle { int radius, color ; int x, y ; float getarea() { return 3.14159

More information

JAVA PROGRAMMING 실습 02. 표준 입출력

JAVA PROGRAMMING 실습 02. 표준 입출력 # 메소드의구조자주반복하여사용하는내용에대해특정이름으로정의한묶음 반환형메소드이름 ( 매개변수 ) { 실행문장 1; : 실행문장 N; } 메소드의종류 Call By Name : 메서드의이름에의해호출되는메서드로특정매개변수없이실행 Call By Value : 메서드를이름으로호출할때특정매개변수를전달하여그값을기초로실행하는메서드 Call By Reference : 메서드호출시매개변수로사용되는값이특정위치를참조하는

More information