티스토리 뷰
동적바인딩 예시
Animal dog = new Dog();
Animal cat = new Cat();
dog.makeSound(); // "강아지가 멍멍 짖습니다."
cat.makeSound(); // "고양이가 야옹 소리를 낸다."
class Animal {
public void makeSound() {
System.out.println("동물이 소리를 낸다.");
}
}
class Dog extends Animal {
public void makeSound() {
System.out.println("강아지가 멍멍 짖습니다.");
}
}
class Cat extends Animal {
public void makeSound() {
System.out.println("고양이가 야옹 소리를 낸다.");
}
}
ArraList 예제
package pkg2;
import java.util.ArrayList;
import java.util.Scanner;
class Book {
public String title;
public int score;
//getTitle setTitle함수 만들기
public Book(String title, int score) {
this.title = title;
this.score= score;
}
public Book() {
}
void setTitle(String title) {
this.title = title;
}
String getTitle() {
return title;
}
void setScore(int score) {
this.score = score;
}
int getScore() {
return score;
}
public String toString() {
return "제목 :"+ title + "평점: "+ score;
}
}
public class Ex07_0704 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner (System.in);
ArrayList <Book> list = new ArrayList <Book>();
Book b[] = new Book[100];
for(int i=0;i<b.length;i++) {
b[i]= new Book(null,0);
}
while(true){
System.out.println("================================");
System.out.println("1. 책 등록");
System.out.println("2. 책 검색"); //제목을 넣으면 평점 알려주기
System.out.println("3. 모든 책 출력");
System.out.println("4. 종료");
System.out.println("================================");
System.out.println("번호를 입력하시오: ");
int num = sc.nextInt();//숫자를 읽고 입력버퍼에 개행문자가 남아있다
sc.nextLine();//앞에 nextInt이면 개행문자 소진
switch(num) {
case 1: {// 책 등록
System.out.println("제목: ");
String title = sc.nextLine(); //String 타입
System.out.print("평점: ");
int score = sc.nextInt(); //메서드안은 지역변수
sc.nextLine(); // 앞에 nextInt이면 개행 문자 소진
list.add(new Book(title, score)); //ArrayList<Book>
break;
}
case 2: {//책 검색
System.out.println("검색할 책의 제목을 입력하시오: ");
String searchTitle = sc.nextLine();
boolean found = false;
for(Book obj : list) { //걍 외우기
if(obj.title.equals(searchTitle)) {
System.out.println(obj.getTitle()+"의 평점은"+ obj.getScore()+"입니다.");
found = true;
break;
}
}
if(!found ) {
System.out.println("검색한 책이 존재하지않는다");
}
break;//이거 쓰기
}
case 3:{//모든 책 출력
for(Book obj : list) {
System.out.println(obj);
}
break;
}
case 4: {//종료
System.out.println("프로그램을 종료합니다.");
}
default:{
System.out.println("잘못된 번호를 입력하였습니다.");
}
}
}
}
}
배열 선언
int[] score; String[] name;
int score[]; String name[];
int[] score; // 배열을 다루기위한 참조 변수 선언
score = new int[길이]; // 실제 저장공간을 생성
String 클래스는 char[] 와 메서드기능을 결합한 것
String 클래스는 내용 변경할 수 없다 read only
Stirng a = "a";
String b = "b";
a = a+b; // ab라는 새로운 문자열이 만들어지는 것이다~!
String 클래스의 주요 메서드
1. char charAt(int index)
String str = "abc";
char ch = str.charAt(1);
2. int length()
3. String substring(int from, int to)
4. boolean equals(Object obj) //문자열 비교할때 == 사용하는 것이아님
String str = "abc";
if(str.equals("abc")){
}
5. char[] toCharArray()
Arrays로 배열 다루기
문자열의 비교와 출력 equals(), toString()
int [] arr = {0,1};
int [][] arr2 = {{11,12}, {21,22}};
int [][] arr3 = {{11,12}, {21,22}};
System.out.println(Arrays.toString(arr));
System.out.println(Arrays.deepToString(arr2));
System.out.println(Arrays.deepEquals(arr2,arr3)); //true
int [] arr = {0,1,2};
Arrays.sort(arr); //배열 arr을 정렬한
int [] arr2 = Arrays.copyOf(arr, arr.length);
int [] arr3 = Arrays.copyOf(arr, 3);
int [] arr4 = Arrays.copyOf(arr, 7); //나머지는 0으로 채워넣
int [] arr5 = Arrays.copyOfRange(arr, 2, 4);
생성자는 인스턴스가 실행될때 생성되는 인스턴스 초기화 메서드!
this() 같은 클래스의 다른 생성자를 호출할때 사용
오버라이딩 규칙
package pkg2;
class Parent8{
void print8() {
System.out.println("부모");
}
}
class Child8 extends Parent8{
void print8() {
System.out.println("자식");
}
}
public class Ex13_0704 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Parent8 p = new Child8();
p.print8();
//Child8 c = (Child8)p; //
//c.print8(); //
}
}
//답 : 자식
package pkg2;
class Animal {
public static void A() {
System.out.println("static method in Animal");
}
}
class Dog extends Animal{
public static void A() {
System.out.println("static method in Dog");
}
}
public class Ex11_0704 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Animal a = new Dog();
a.A();
//Dog dog = new Dog(); //
//Animal a = dog; //
//dog.A();
}
}
//답 :static method in Animal
'Java' 카테고리의 다른 글
입출력 스트림과 파일 입출력 (0) | 2023.07.13 |
---|---|
12장 Collection FrameWork Generics (0) | 2023.07.10 |
object oriented programming 개념 정리 (0) | 2023.07.08 |
11장 Collection FrameWork (0) | 2023.07.06 |
9장 Java.lang package & util classes (0) | 2023.07.04 |