class Car {
String name;
int speed;
void run() { System.out.println(name + "이 달립니다!"); }
}
public class Main {
public static void main(String[] args){
Car c = new Car();
c.name = "소나타";
c.run();
}
}
출력:
소나타이 달립니다!
class : 객체의 속성(필드)과 동작(메서드)을 정의.new : 객체를 메모리에 생성.this : 현재 객체 자신을 가리킴.class A {
int x;
A(int x){ this.x = x; }
}
public class Main {
public static void main(String[] args){
A obj1 = new A(5);
A obj2 = obj1;
obj2.x = 10;
System.out.println(obj1.x);
}
}
obj1과 obj2는 같은 객체를 참조한다.obj2.x = 10은 obj1.x에도 반영된다.정답:
10
class Parent {
void show() { System.out.println("Parent"); }
}
class Child extends Parent {
void show() { System.out.println("Child"); }
}
public class Main {
public static void main(String[] args){
Parent p = new Child();
p.show();
}
}
출력:
Child
Child) 기준으로 메서드 결정class Parent {
int x = 100;
int getX() { return x; }
}
class Child extends Parent {
int x = 4000;
int getX() { return x * 2; }
}
public class Main {
public static void main(String[] args){
Parent p = new Child();
System.out.println(p.getX());
}
}
getX()는 오버라이딩 → 객체 타입(Child) 기준 호출x는 필드 숨김 → 참조 타입(Parent) 기준 사용되지 않음정답:
8000
static은 클래스 단위로 공유되는 영역이다. 모든 인스턴스가 같은 값을 본다.class Counter {
static int count = 0;
Counter() { count++; }
}
public class Main {
public static void main(String[] args){
new Counter();
new Counter();
System.out.println(Counter.count);
}
}
출력:
2
class Connection {
private static Connection _inst = null;
private int count = 0;
static Connection get() {
if(_inst == null)
_inst = new Connection();
return _inst;
}
void count(){ count++; }
int getCount(){ return count; }
}
public class Main {
public static void main(String[] args){
Connection c1 = Connection.get();
c1.count();
Connection c2 = Connection.get();
c2.count();
System.out.println(c1.getCount());
}
}
static은 클래스 단위로 단 하나만 존재한다.Connection.get()은 항상 동일 객체 반환.count가 누적되어 2가 된다.정답:
2
abstract 클래스는 상속을 위한 틀abstract class Vehicle {
abstract String getName(String val);
void start(){ System.out.println("출발!"); }
}
class Car extends Vehicle {
String getName(String val){ return "Car name : " + val; }
}
abstract class Vehicle {
private String name;
abstract String getName(String val);
public String getName() { return "vehicle name:" + name; }
public void setName(String val){ name = val; }
}
class Car extends Vehicle {
public Car(String val){ setName(val); }
public String getName(String val){ return "Car name : " + val; }
}
public class Main {
public static void main(String[] args){
Vehicle obj = new Car("Spark");
System.out.println(obj.getName());
}
}
obj.getName()은 매개변수 없는 오버로딩 메서드 호출name 필드는 "Spark"로 설정되어 있다.정답:
vehicle name:Spark
try {
int x = 5 / 0;
} catch (ArithmeticException e) {
System.out.println("0으로 나눌 수 없습니다");
} finally {
System.out.println("항상 실행");
}
public class Main {
public static void main(String[] args){
int a = 5, b = 0;
try {
System.out.print(a / b);
} catch (ArithmeticException e) {
System.out.print("출력1");
} finally {
System.out.print("출력2");
}
}
}
5 / 0 → ArithmeticException 발생catch로 "출력1" 출력, finally는 항상 실행정답:
출력1출력2
int[] arr = {1, 2, 3};
String[] s = {"A", "B"};
public class Main {
public static void change(String[] data, String s){
data[0] = s;
s = "Z";
}
public static void main(String[] args){
String data[] = {"A"};
String s = "B";
change(data, s);
System.out.println(data[0] + s);
}
}
data)은 참조형이라 원소 변경이 반영됨.s)은 값 복사이므로 지역 변경은 영향 없음.정답:
BB
interface F { int apply(int x) throws Exception; }
public class Main {
static int run(F f){
try { return f.apply(3); }
catch(Exception e){ return 7; }
}
}
public class Main {
static interface F { int apply(int x) throws Exception; }
static int run(F f){
try { return f.apply(3); }
catch(Exception e){ return 7; }
}
public static void main(String[] args){
F f = (x) -> {
if(x > 2) throw new Exception();
return x * 2;
};
System.out.println(run(f) + run((int n) -> n + 9));
}
}
run(f) → 예외 발생 → 7run((n)->n+9) → 3+9=127+12=19정답:
19
| 비교 방식 | 의미 |
|---|---|
== | 참조 주소 비교 |
.equals() | 실제 내용 비교 |
String str1 = "Programming";
String str2 = "Programming";
String str3 = new String("Programming");
System.out.println(str1==str2);
System.out.println(str1==str3);
System.out.println(str1.equals(str3));
str1 == str2 → true (리터럴 동일 참조)str1 == str3 → false (new로 별도 객체).equals() → true (내용 동일)정답:
true
false
true
static int func(int[] a, int st, int end) {
if (st >= end) return 0;
int mid = (st + end) / 2;
return a[mid] + Math.max(func(a, st, mid), func(a, mid + 1, end));
}
public static void main(String[] args){
int[] data = {3,5,8,12,17};
System.out.println(func(data,0,data.length-1));
}
정답:
20
오버로딩(Overloading)
: 같은 이름, 다른 매개변수로 여러 메서드를 정의하는 것
→ 컴파일 시점에 결정됨 (정적 바인딩)
오버라이딩(Overriding)
: 상속 관계에서 부모 메서드를 재정의하는 것
→ 실행 시점에 결정됨 (동적 바인딩)
class Parent {
void show(){ System.out.println("Parent"); }
}
class Child extends Parent {
void show(){ System.out.println("Child"); }
}
public class Main {
public static class Parent {
public int x(int i){ return i + 2; }
public static String id(){ return "P"; }
}
public static class Child extends Parent {
public int x(int i){ return i + 3; }
public String x(String s){ return s + "R"; }
public static String id(){ return "C"; }
}
public static void main(String[] args){
Parent ref = new Child();
System.out.println(ref.x(2) + ref.id());
}
}
x(2) → 동적 바인딩으로 Child.x(int) 호출 → 5id() → 정적 메서드, 참조 타입 기준 → Parent.id() = “P”정답:
5P
static은 클래스 전체에서 공유되는 변수이다.
인스턴스와 무관하게 하나만 존재한다.
class Counter {
static int count = 0;
Counter(){ count++; }
}
모든 객체가 하나의 count를 공유한다.
class Connection {
private static Connection inst = null;
private int count = 0;
static Connection get(){
if(inst == null) inst = new Connection();
return inst;
}
void count(){ count++; }
int getCount(){ return count; }
}
public class Main {
public static void main(String[] args){
Connection c1 = Connection.get();
c1.count();
Connection c2 = Connection.get();
c2.count();
Connection c3 = Connection.get();
c3.count();
System.out.println(c1.getCount());
}
}
count() 총 3회 실행 → count = 3정답:
3
추상 클래스:
abstract 메서드는 몸체가 없음abstract class Vehicle {
String name;
abstract String getName(String val);
public String getName(){ return "Vehicle name: " + name; }
}
class Car extends Vehicle {
public Car(String val){ name = val; }
public String getName(String val){ return "Car name: " + val; }
}
public class Main {
public static void main(String[] args){
Vehicle obj = new Car("Spark");
System.out.println(obj.getName());
}
}
"Vehicle name: Spark"정답:
Vehicle name: Spark
try {
int x = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("0으로 나눌 수 없습니다");
} finally {
System.out.println("항상 실행");
}
public class Main {
public static void main(String[] args){
int a = 5, b = 0;
try {
System.out.println(a/b);
} catch(ArithmeticException e) {
System.out.print("출력1");
} finally {
System.out.print("출력5");
}
}
}
a/b → 0으로 나눔 → ArithmeticException 발생"출력1""출력5"정답:
출력1출력5
== : 참조 주소 비교.equals() : 문자열 내용 비교String str1 = "Programming";
String str2 = "Programming";
String str3 = new String("Programming");
System.out.println(str1 == str2);
System.out.println(str1 == str3);
System.out.println(str1.equals(str3));
str1 == str2 → truestr1 == str3 → false.equals() → true정답:
true
false
true
public class Main {
static class BO {
public int v;
public BO(int v){ this.v = v; }
}
public static void main(String[] args){
BO a = new BO(1);
BO b = new BO(2);
BO c = new BO(3);
BO[] arr = {a,b,c};
BO t = arr[0];
arr[0] = arr[2];
arr[2] = t;
arr[1].v = arr[0].v;
System.out.println(a.v + "a" + b.v + "b" + c.v);
}
}
arr = {c,b,a}b.v = c.v → 3a=1, b=3, c=3정답:
1a3b3
int func(int[] a, int st, int end){
if(st >= end) return 0;
int mid = (st + end) / 2;
return a[mid] + Math.max(func(a, st, mid), func(a, mid+1, end));
}
배열 {3,5,8,12,17} 입력 시
정답:
20
@FunctionalInterface
interface F { int apply(int x) throws Exception; }
F f = (x) -> {
if(x > 2) throw new Exception();
return x * 2;
};
System.out.print(run(f) + run((int n) -> n + 9));
정답:
19
throws : 메서드가 예외를 호출자에게 던짐throw : 예외를 실제 발생시킴public class ExceptionHandling {
public static void main(String[] args){
int sum = 0;
try {
func();
} catch (NullPointerException e) {
sum += 1;
} catch (Exception e) {
sum += 10;
} finally {
sum += 100;
}
System.out.print(sum);
}
static void func() throws Exception {
throw new NullPointerException();
}
}
func() → NullPointerException 발생 → 첫 번째 catch 실행 → +1정답:
101
class Main {
public static class Collection<T>{
T value;
Collection(T t){ value = t; }
void print(){
new Printer().print(value);
}
class Printer {
void print(Integer a){ System.out.print("A" + a); }
void print(Object a){ System.out.print("B" + a); }
void print(Number a){ System.out.print("C" + a); }
}
}
public static void main(String[] args){
new Collection<>(0).print();
}
}
T = Integerprint(Integer) 선택 → "A0"정답:
A0
public class Main {
public static void main(String[] args){
new Child();
System.out.println(Parent.total);
}
}
class Parent {
static int total = 0;
int v = 1;
Parent(){
total += (++v);
show();
}
public void show(){ total += total; }
}
class Child extends Parent {
int v = 10;
Child(){
v += 2;
total += v++;
show();
}
public void show(){ total += total * 2; }
}
total=2, show()(자식 버전 호출) → 6v=10→12, total+=12→18, show()(자식) → 18+36=54정답:
54