정보처리기사 실기 java
Java----------------------------------------
예제 -----
-----
class ClassA {
int a = 10;
int funcAdd(int x, int y) {
return x + y + a;
// 3 + 6 + 10 == 19
}
}
public class Test {
//public은 클래스, 변수, 메서드 등에 부여하는 접근 제어자(Access Modifier)로, "어디서든 누구나 접근할 수 있다"는 완전 공개의 의미를 가집니다.
public static void main(String[] args) {
//static은 '클래스에 속한' 또는 '공통적인'이라는 의미를 가집니다. 객체(인스턴스)를 생성하지 않고도 메모리에 고정되어 변수나 메서드를 바로 사용할 수 있게 해주는 키워드입니다.
//void는 메서드가 실행을 마치고 호출한 곳으로 반환(return)할 결과값이 전혀 없음을 의미하는 키워드입니다.
int x = 3, y = 6, r;
ClassA cal = new ClassA();
r = cal.funcAdd(x, y);
System.out.print(r);
}
}
-----
public class Test {
public static void main(String[] args) {
String str = "agile";
int x[] = {1, 2, 3, 4, 5};
char y[] = new char[5];
int i = 0;
while (i < str.length()) {
y[i] = str.charAt(i);
//.charAt(i)은 i번째 있는 문자를 저장하는 거.
i++;
//y[] ===> {"a", "g", "i", "l", "e"}
}
// i == 5
for (int p : x) {
//for (int p : x) 구문은 배열이나 컬렉션의 모든 요소를 순회할 때 사용하는 '향상된 for문(Enhanced for loop)' 또는 'for-each문'입니다.
//x: 순회할 대상 (배열 또는 List와 같은 컬렉션)int p: x에서 꺼낸 요소를 임시로 담을 변수 (반복문 안에서 p를 사용해 요소에 접근)동작 방식: 루프가 돌 때마다 x[0], x[1], x[2] 등의 값이 자동으로 p에 할당되며, 요소의 개수만큼 반복하고 끝납니다.
i--;
System.out.print(y[i]);
System.out.print(p + " ");
//출력값 e1 l2 i3 g4 a5
}
}
}
------
public class Groom {
static void change(char arr[]) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == 'b') arr[i] = 'c';
// {'a', 'c', 'c', 'c', 'c', 'd', 'a'}
else if (i == arr.length - 1) arr[i] = arr[i - 1];
// {'a', 'c', 'c', 'c', 'c', 'd', 'd'}
else arr[i] = arr[i + 1];
// {'b', 'c', 'b', 'c', 'd', 'a', 'a'}
}
}
static void prtarr(char arr[]) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
//출력값 bcbcdaa
}
}
public static void main(String[] args) {
char[] a = {'a', 'b', 'c', 'b', 'c', 'd', 'a'};
change(a);
prtarr(a);
}
}
------
public class Groom {
static int[] MakeArray() {
int[] tempArr = new int[5];
for (int i = 0; i < tempArr.length; i++) {
tempArr[i] = i;
}
return tempArr;
}
public static void main(String[] args) {
int[] myArr;
myArr =MakeArray();
//[][][][][] ===> 0, 1, 2, 3, 4
for (int i = 0; i < myArr.length; i++) {
System.out.print(myArr[i]);
//최종값 01234
}
}
}
------
public class Groomie {
public static void main(String[] args) {
int i, j;
for(j = 1, i = 1; i <= 5; i++) {
j *= i;
//i == 1 ===> j == 1
//i == 2 ===> j == 2
//i == 3 ===> j == 6
//i == 4 ===> j == 24
//i == 5 ===> j == 120
System.out.print(i); //잘보기 이거
//1*2*3*4*5=120
if (i == 5) {
System.out.print("=");
System.out.print(j);
}
else {
System.out.print("*");
}
}
}
}
------
public class Groom {
public static void main(String[] args) {
A b = new B();
b.top();
b.bottom();
//출력값 BDCDD
}
}
class A {
public void top() {
System.out.print("A");
bottom();
}
public void bottom() {
System.out.print("B");
bottom();
//이거는 오버라이딩 된거 따라가는거. 아래꺼
//##### 오버라이딩
}
}
class B extends A {
public void top() {
super.bottom();
System.out.print("C");
this.bottom();
//BDCD
}
public void bottom() {
System.out.print("D");
//D
}
}
------
public class Groom {
public static void main(String[] args) {
int[][] a =new int[3][5];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 5; j++) {
a[i][j] = j * 2 + (i + 1);
//i == 0, j == 0 ===> [0][0] -> 1
//i == 0, j == 1 ===> [0][1] -> 3
//i == 0, j == 2 ===> [0][2] -> 5
//i == 0, j == 3 ===> [0][3] -> 7
//i == 0, j == 9 ===> [0][4] -> 9
//2 4 6 8 10
//3 5 7 9 11
System.out.print(a[i][j] + " ");
}
System.out.println();
/*
최종값
1 3 5 7 9
2 4 6 8 10
3 5 7 9 11
*/
}
}
}
------
public class Main {
public static void main(String[] args) {
int i = 0;
int sum = 0;
while (i < 1) {
i++;
if (i % 2 == 1)
continue;
sum += i;
//i가 0만 가능하므로, sum == 0
}
System.out.println(sum);
}
}
------
public class Groom {
public static void main(String[] args) {
int[] result = new int[5];
int[] arr = {20, 80, 10, 70, 50};
for(int i = 0; i < 5; i++) {
result[i] = 1;
for(int j = 0; j < 5; j++) {
if(arr[i] < arr[j]) result[i]++;
//20일 때는 80, 70, 50이 더 커서 result[0] == 4
//80일 때는 result[1] == 1
//10일 때는 나머지들이 더 커서 result[2] == 5
//70일 때 80만 더 커서 result[3] == 2
//50일 때는 70, 80만 result[4] == 3
}
}
for (int i = 0; i < 5; i++) {
System.out.print(result[i]);
//41523
}
}
}
------
public class Mypro1 {
public static void main(String[] args) {
Mypro1 a = new Mypro2();
Mypro1 b = new Mypro2();
System.out.println(a.compute(5, 3) + b.compute(5, 3));
//20
}
int compute(int x, int y) {
return x + y;
}
}
class Mypro2 extends Mypro1 {
int compute(int x, int y) {
return x - y + super.compute(x, y);
//5 - 3 + 5 + 3 == 10
}
}
------
class Parent {
int func(int n) {
if (n <= 1)
return n;
return func(n - 1) + func(n - 2);
}
}
class Child extends Parent {
int func(int n) {
if (n <= 1) {
return n;
}
return func(n - 1) + func(n - 3);
//func(7) -> f6 + f4
//f6 + f4 -> f5 + f3 + f3 + f1
//f5 + f3 + f3 + f1 -> f4 + f2 + f2 + f0 + f2 + f0 +f1
//f4 + f2 + f2 + f0 + f2 + f0 +f1 -> f3 + f1 + f1 + f-1 + f1 + f-1 + f0 + f1 + f-1 + f0 +f1
//-> f2 + f0 + f1 + f1 + f-1 + f1 + f-1 + f0 + f1 + f-1 + f0 +f1
//-> f1 + f-1 + f0 + f1 + f1 + f-1 + f1 + f-1 + f0 + f1 + f-1 + f0 +f1
//1이 6개, -1이 4개라서 최종값은 2를 넘겨줌.
}
}
public class Groom {
public static void main(String[] args) {
Parent obj = new Child();
System.out.print(obj.func(7));
//2
}
}
------
public class Main {
public static void main(String[] args) {
int a[][] = {{1, 2, 3, 4, 5}, {6, 7}};
System.out.println(a[0].length);
//5
System.out.println(a[1].length);
//2
System.out.println(a[0][0]);
//1
System.out.println(a[0][1]);
//2
System.out.println(a[1][1]);
//7
}
}
------
public class Groom {
public static void main(String[] args) {
int[] digit = new int[8];
int i = 0; int n = 10;
while(n >= 1) {
digit[i++] = n % 2;
n /= 2;
}
//[0] == 0, n == 5, [1] == 1, n == 2.5, [2] == 0, n == 1.25, [3] == 1, n == 0.625, [4] == 0부터는 계속 0
for (i = 7; i >= 0; i--) {
System.out.print(digit[i]);
//출력값 00001010이 됨.
}
}
}
------
class Animal {
public void speak() {
System.out.println("Animal");
}
}
class Dog extends Animal {
public void speak() {
System.out.println("barking");
}
}
class Cat extends Animal {
public void speak() {
System.out.println("meowing");
}
}
public class Groom {
public static void main(String[] args) {
Animal a;
//빈칸 채우기 문제
a = new Dog();
a.speak();
//빈칸 채우기 문제
a = new Cat();
a.speak();
}
}
/*
출력값
barking
meowing
*/
-----
class Point {
int x;
int y;
}
public class Groom {
public static void main(String[] args) {
Point m = new Point();
m.x = 1000;
//Point의 x는 1000
calc(m);
//1000 / 10 == 100
getValue(m);
//100 위에꺼가 100이니, 받아서
System.out.printf("%d", m.y);
//최종 출력값이 100
}
static void calc(Point s) {
s.x /= 10;
}
static void getValue(Point p) {
p.y = p.x;
}
}
-----
public class test {
public static void main(String[] args) {
int result = 0;
for (int i = 1; i < 10; i++) {
//1, 2, 3, 4, 5, 6, 7, 8, 9
if (i % 3 == 0 && i % 2 != 0)
result = result + i;
//3과 9만 result에 더해짐.
}
System.out.print(result);
//출력값 12
}
}
------
class Parent {
private int a;
//private은 해당 변수나 메서드를 선언된 클래스 내부에서만 접근 가능하도록 제한하는 가장 강력한 접근 제어자입니다. 외부 클래스나 객체에서는 직접적인 접근이 불가능하여 데이터 보호와 캡슐화에 사용됩니다.
public Parent (int a) {
this.a = a;
}
public void display() {
System.out.print("Birth = " + a);
}
}
class Child extends Parent {
public Child(int val) {
super(val);
super.display();
/*
super(val);은 부모 클래스(Parent)의 생성자를 호출하는 명령입니다.
자식 클래스의 인스턴스를 생성할 때 부모 클래스의 초기화 작업이 먼저 이루어져야 하므로,
부모 클래스에 정의된 생성자인 public Parent(int a)를 찾아 매개변수 val을 전달하는 역할을 합니다.
핵심 동작 원리부모 생성자 강제 호출: Parent 클래스에는 기본 생성자(매개변수가 없는 생성자)가 없고
int a를 받는 생성자만 존재합니다. 따라서 자식 클래스에서는 반드시 super(val);을 명시하여 부모의 생성자를 채워주어야만 컴파일 에러가 나지 않습니다.첫 줄 위치 법칙: super()는 자식 클래스 생성자의 반드시 첫 번째 줄에 위치해야 합니다. 부모가 메모리에 먼저 올라가야 자식이 생성될 수 있기 때문입니다.
*/
}
}
public class Groom {
public static void main(String[] args) {
Child Birth = new Child(2024);
//Birth = 2024가 출력값
}
}
------
class Parent {
protected int value = 10;
public void printValue() {
System.out.println("Parent value: " + value);
}
}
class Child extends Parent {
protected int value = 20;
public void updateValue(int n) {
this.value = n;
}
public void printValue() {
System.out.println("Child value: " + value);
}
}
public class Main {
public static void main(String[] args) {
Parent parent = new Parent();
Child child = new Child();
parent.printValue();
child.printValue();
/*
Parent value: 10
Child value: 20
*/
child.updateValue(30);
//이거로 인해서 class Child의 value가 30이 된다.
parent.printValue();
child.printValue();
/*
Parent value: 10
Child value: 30
*/
}
}
-----
class DivSum {
private int sum;
public DivSum() {
sum = 0;
}
public void accSum(int num) {
for (int i = 1; i < num; i++) {
if (num % i == 0) {
sum += i;
}
}
}
public int getSum() {
return sum;
}
}
public class Main {
public static void main(String[] args) {
int i = 10;
DivSum ds = new DivSum();
ds.accSum(i);
int result = ds.getSum();
System.out.println(i + "보다 작은 약수의 합" + result);
}
}
/*
자바의 객체 지향 프로그래밍 관점에서 원리를 요약하면 다음과 같습니다.📌 핵심 원리인스턴스 변수 공유: sum은 DivSum 클래스의 인스턴스 변수(필드)입니다. 같은 객체(ds) 안에서 생성된 메서드들은 이 변수를 함께 사용합니다.상태의 변경: ds.accSum(i);를 호출하면 반복문을 돌며 ds 객체의 sum 변수 값을 직접 누적하여 변경합니다.변경된 상태 읽기: 그 후 ds.getSum();을 호출하면 앞서 변경되어 저장된 sum 변수의 현재 값을 그대로 반환합니다.🏃♂️ 실행 순서별 데이터 변화객체 생성 (DivSum ds = new DivSum();)ds 객체가 메모리에 만들어지며 sum 변수는 0으로 초기화됩니다. (ds.sum == 0)메서드 실행 (ds.accSum(10);)10의 약수(1, 2, 5)를 구합니다.ds 객체 내부의 sum 변수에 이 값들을 더합니다. (\(0 + 1 + 2 + 5 = 8\))이 시점에서 ds 객체의 sum은 8이 됩니다. (ds.sum == 8)결과 가져오기 (int result = ds.getSum();)ds 객체의 현재 sum 값인 8을 반환하여 result 변수에 저장합니다.만약 ds.accSum(i); 코드를 생략하고 바로 ds.getSum();을 호출한다면, sum 변수 값이 변하지 않아 초기값인 0이 반환됩니다.
10보다 작은 약수의 합8
*/
------
class Animal {
public void makeSound() {
System.out.println("동물은 소리를");
}
}
class Cat extends Animal {
public void makeSound() {
super.makeSound();
System.out.println("야옹!");
}
}
class Dog extends Animal {
public void makeSound() {
super.makeSound();
System.out.println("멍멍멍!");
}
}
public class Main {
public static void main(String[] args) {
Animal animal1 = new Cat();
Animal animal2 = new Dog();
animal1.makeSound();
animal2.makeSound();
}
}
/*
출력값
동물은 소리를
야옹!
동물은 소리를
멍멍멍!
*/
------
class Parent {
void printNumbers() {
System.out.println("Parent class");
for(int i = 1; i <= 5; i++) {
System.out.print(i + " ");
}
System.out.println();
}
}
class Child extends Parent {
void printNumbers() {
System.out.println("Child class: ");
for(int i = 5; i >= 1; i--) {
System.out.print(i + " ");
}
System.out.println();
}
}
public class OverridingExample {
public static void main(String[] args) {
Parent parent = new Parent();
parent.printNumbers();
Child child = new Child();
child.printNumbers();
}
}
/*
출력값
Parent class
1 2 3 4 5
Child class:
5 4 3 2 1
*/
-----
class A {
int cost = 10;
A() {
System.out.print("A");
outputCost();
}
void outputCost() {
System.out.print(cost);
}
}
class B extends A {
int cost = 20;
B() {
System.out.print("B");
outputCost();
}
void outputCost() {
System.out.print(cost);
}
}
public class groom {
public static void main(String[] args) {
A a = new B();
System.out.print(a.cost);
}
}
//A0B2010
1. A a = new B(); 객체 생성 시작자식 클래스 B를 생성할 때, 자바는 부모 클래스 A의 생성자를 먼저 호출합니다.이때 메모리상에는 A 영역의 cost(10)와 B 영역의 cost(20)가 각각 독립적으로 존재하게 되며, 실제 인스턴스의 타입은 B입니다.2. 부모 클래스 A 생성자 실행System.out.print("A");가 실행되어 화면에 A가 출력됩니다.이어서 outputCost(); 메서드를 호출합니다.[핵심 - 가상 메서드 호출] 자바는 부모 생성자 안에서 메서드를 호출하더라도, 실제 생성된 인스턴스 타입(B)의 오버라이딩된 메서드를 먼저 찾습니다. 따라서 A의 메서드가 아닌 B 클래스의 outputCost()가 실행됩니다.[핵심 - 변수 초기화 시점] B 클래스의 outputCost()는 B 영역의 cost를 출력하려고 합니다. 하지만 아직 B 클래스의 생성자 및 필드 초기화(cost = 20)가 실행되기 전이므로, B 영역의 cost는 자바 기본값인 0인 상태입니다.결과적으로 0이 출력됩니다. (현재까지 출력: A0)3. 자식 클래스 B 생성자 실행부모 생성자 실행이 끝났으므로, B 클래스의 필드인 cost가 20으로 초기화됩니다.System.out.print("B");가 실행되어 B가 출력됩니다.이어서 outputCost(); 메서드가 호출되며, 이번에는 cost가 20으로 초기화된 상태이므로 20이 출력됩니다. (현재까지 출력: A0B20)4. System.out.print(a.cost); 실행[핵심 - 변수의 다형성] 메서드와 달리 멤버 변수(필드)는 오버라이딩되지 않습니다.변수에 접근할 때는 참조 변수의 타입을 따릅니다. 변수 a의 타입이 A로 선언되었기 때문에, a.cost는 B 클래스의 변수가 아닌 A 클래스의 cost(10)를 가리키게 됩니다.결과적으로 10이 출력됩니다.
#####
질문하신 대로 처음에 보셨던 이 코드에서는 자식 클래스가 부모의 영향을 직접적으로 받아서 0이라는 엉뚱한 값이 출력되었습니다.방금 전 OverridingExample 코드(출력에 영향이 없던 코드)와 이 코드(영향을 받아서 0이 나온 코드)의 결정적인 차이점은 바로 "메서드가 호출되는 시점과 위치"에 있습니다.이 코드에서 자식이 영향을 받아 0이 출력된 이유를 2가지 핵심 차이점으로 명확하게 짚어드리겠습니다.차이점 1: 메서드가 '생성자(Constructor)' 내부에서 호출되었습니다 (가장 중요)영향이 없던 코드: main 메서드에서 이미 객체 생성이 완벽히 끝난 뒤에 child.printNumbers();를 호출했습니다. 이때는 자식의 필드나 메서드가 모두 메모리에 정상적으로 올라간 상태라 부모의 영향을 받지 않습니다.영향을 받은 이 코드: 객체가 만들어지는 도중, 즉 부모 클래스 A ➡️ 자식 클래스 B 순서로 생성자가 실행되는 도중에 메서드가 호출되었습니다.차이점 2: 자식의 필드가 초기화되기 전에 메서드가 실행되었습니다자바에서 new B();를 하면 다음과 같은 순서로 메모리가 세팅됩니다.[1단계] 메모리에 A와 B 자리가 만들어지고, 모든 필드는 기본값(0)으로 임시 세팅됩니다.[2단계] 부모 클래스 A 개발 선언부로 이동하여 cost = 10으로 초기화된 후, 부모 생성자 A()가 먼저 실행됩니다.[3단계] 부모 생성자 안에서 outputCost()를 호출합니다. 오버라이딩 규칙에 따라 자식(B)의 outputCost()가 실행됩니다.[문제 발생] 자식의 메서드가 실행되었는데, 정작 자식 클래스의 cost = 20이라는 진짜 초기화 코드(4단계)는 아직 실행되기도 전입니다. 부모 생성자가 완전히 끝나야 자식 차례가 오기 때문입니다.[결과] 아직 초기화되지 못해 기본값 0 상태인 자식의 cost가 화면에 출력되어 버립니다. (A0이 나오는 이유)💡 한 줄 요약이전 코드: 객체 생성이 완전히 끝난 후에 자식 메서드를 호출해서 영향이 없었음.현재 코드: 객체가 생성되는 도중에(부모 생성자 안에서) 자식 메서드를 가로채어 호출하는 바람에, 자식의 변수(cost=20)가 채 채워지기도 전에 0을 출력하는 조기 호출 버그(영향)가 발생함.자바에서는 이처럼 부모 생성자 안에서 오버라이딩이 가능한 메서드를 호출하는 것을 위험한 안티 패턴(Anti-pattern)으로 규정하고 권장하지 않습니다.
-----
public class Groom {
public static void main(String[] args) {
String base = "Hello Groom";
char ch = 'o';
for (int i = 0; i < base.length(); i++) {
if (ch == base.charAt(i))
base = base.substring(0, i) + '*' + base.substring(i + 1);
else
base = base.substring(0, i) + '-' + base.substring(i + 1);
}
System.out.println(base);
}
}
//출력값 ----*---**-
//base.substring(0, i)은 0에서 i - 1 인덱스까지 base.substring(i + 1)는 i + 1에서부터 끝까지
/*
처음 시작할 때 base는 "Hello Groom"이 맞습니다. 하지만 반복문(for)이 한 바퀴 돌 때마다 base 변수 자체를 새로 바뀐 문자열로 계속 덮어씁니다(base = ...).i=2부터 i=4까지 변하는 과정을 눈으로 따라가 보겠습니다.① 2번째 바퀴 (i = 2, 'l'을 바꾸는 차례)바꾸기 전 base 상태: "--llo Groom" (앞의 2글자는 이미 이전 바퀴에서 --로 바뀐 상태)코드 실행: substring(0, 2) + '-' + substring(3)앞부분: "--"바꿀 글자: "-"뒷부분: "lo Groom" (여기에 원래 글자가 아직 남아있음!)바뀐 후 base 상태: "---lo Groom"② 3번째 바퀴 (i = 3, 다음 'l'을 바꾸는 차례)바꾸기 전 base 상태: "---lo Groom" (방금 만든 따끈따끈한 문자열을 가져옴)코드 실행: substring(0, 3) + '-' + substring(4)앞부분: "---"바꿀 글자: "-"뒷부분: "o Groom" (원래 글자가 한 칸 더 줄어듦)바뀐 후 base 상태: "----o Groom"③ 4번째 바퀴 (i = 4, 'o'를 바꾸는 차례)바꾸기 전 base 상태: "----o Groom"코드 실행: substring(0, 4) + '*' + substring(5)앞부분: "----"바꿀 글자: "*" (조건이 참이므로 * 삽입)뒷부분: " Groom" (이제 'H, e, l, l, o'는 흔적도 없이 사라짐)바뀐 후 base 상태: "----* Groom"
*/
------
class Parent {
int x = 100;
Parent() {
this(500);
//인자가 없는 new Parent()를 호출했으므로 기본 생성자로 진입합니다.들어가자마자 첫 줄에 있는 this(500);을 만납니다.이 명령은 "잠깐 멈추고, int를 인자로 받는 다른 생성자한테 500을 들고 가라"는 뜻입니다.
}
Parent(int x) {
this.x = x;
}
int getX() {
return x;
}
}
class Child extends Parent {
int x = 4000;
Child() {
this(5000);
}
Child(int x) {
this.x = x;
}
/*
@Override
int getX() {
return x;
}이런식으로 해야지, 5000이 출력됨*/
}
public class Main {
public static void main(String[] args) {
Child obj = new Child();
System.out.println(obj.getX());
}
}
//결과값 500
-----
class Bicycle {
int cadence = 0;
int speed = 0;
int gear = 1;
void changeCadence(int newValue) {
cadence = newValue;
}
void changeGear(int newValue) {
gear = newValue;
}
void speedUp(int increment) {
speed = speed + increment;
}
void applyBrakes(int decrement) {
speed = speed - decrement;
}
void printStates() {
System.out.println("cadence:" +
cadence + " speed:" +
speed + " gear:" + gear);
}
}
class BicycleDemo {
public static void main(String[] args) {
// Create two different
// Bicycle objects
Bicycle bike1 = new Bicycle();
Bicycle bike2 = new Bicycle();
// Invoke methods on
// those objects
bike1.changeCadence(50);
bike1.speedUp(10);
bike1.changeGear(2);
bike1.printStates();
bike2.changeCadence(50);
bike2.speedUp(10);
bike2.changeGear(2);
bike2.changeCadence(40);
bike2.speedUp(10);
bike2.changeGear(3);
bike2.printStates();
}
}
/*
출력값 #####
cadence:50 speed:10 gear:2
cadence:40 speed:20 gear:3
*/
------
class Groom {
int cadence = 0;
int speed = 0;
int gear = 1;
void changeCadence(int newValue) {
cadence = newValue;
}
void main() {
System.out.println(cadence + ", " + speed + ", " + gear);
}
//위와 같이만 하면, 0, 0, 1이 나옴.
//#####https://dev.java/learn/oop/
}
------
public class Groom {
public static void main(String[] args) {
int a = 1, b = 2, c = 3, d = 4;
int max, min;
max = a < b ? b : d;
//max == 2
if (max == 1) {
min = a > c ? c : b;
}
else {
min = b < c ? a : d;
}
//min == 1
System.out.println(min + max);
//결과값 3
}
}
------
abstract class Vehicle {
//자바에서 abstract는 "미완성"을 의미하는 제어자(Modifier)입니다. [1] 클래스와 메서드에 사용할 수 있으며, 핵심은 "구체적인 내용은 하위 클래스(자식)에서 반드시 직접 구현하라"고 강제하는 것입니다.
String name;
abstract public String getName(String val);
public String getName() {
return "Vehicle name: " + name;
}
}
class Car extends Vehicle {
private String name;
//private은 해당 변수, 메서드, 또는 생성자를 선언된 클래스 내부에서만 접근할 수 있도록 제한하는 가장 강력한 접근 제어자입니다. 외부 클래스나 자식 클래스에서는 직접 접근할 수 없습니다.
public Car(String val) {
name = super.name = val;
//super.name은 "자식 클래스(Car)에서 부모 클래스(Vehicle)에 선언된 name 변수를 가리키는 표현
}
public String getName(String val) {
return "Car name: " + val;
}
public String getName(byte val[]) {
//byte val[]은 byte 타입의 데이터들을 저장하는 배열(Array)을 뜻하며, 메서드의 매개변수(Parameter)로 선언되었습니다.
return "Car name: " + val;
}
}
public class Main {
public static void main(String[] args) {
Vehicle obj = new Car("Spark");
System.out.println(obj.getName("good"));
//public String getName(String val)이 작동함.
System.out.println(obj.getName());
//public String getName()이 작동함.
}
}
/*출력값
Car name: good
Vehicle name: Spark
*/
-----
class Static {
public int a = 20;
static int b = 0;
}
public class Test {
public static void main(String[] args) {
int a = 10;
Static.b = a;
Static st = new Static();
System.out.println(Static.b++);
//Static.b = a; 때문에 Static.b는 10
System.out.println(st.b);
//Static.b++ 때문에 st.b는 11
System.out.println(a);
//int a = 10이라서 10
System.out.println(st.a);
//st.a는 20
}
}
-------------
//c언어 문제 보고 만든거
public class Main {
public static void main(String[] args) {
int i = 0, c = 0;
while(i < 10) {
i++;
c *= i;
}
System.out.printf("%d", c);
}
}
결과는 0
//c언어 예제 보고 만든거
class rr {
int r1() {
return 4;
}
int r10() {
return 30 + r1();
}
int r100() {
return 200 + r10();
}
}
public class Main {
public static void main(String[] args) {
rr newbo = new rr();
System.out.println(newbo.r100());
}
}
출력값 234
------
문제 풀었음
public class groomi {
public static void main(String[] args) {
int [][] array = new int [3][5];
int n = 1;
for(int i = 0; i < 3; i++) {
for (int j = 0; j < 5; j++) {
array[i][j] = j * 3 + (i + 1);
System.out.print(array[i][j] + " ");
}
System.out.println();
}
}
}
결과:
1 4 7 10 13
2 5 8 11 14
3 6 9 12 15
--------------------
문제 풀었음
public class groomgroom{
public static void main(String[] args){
int a[] = new int[8];
int i = 0, n = 10;
while(n > 0){ // n >= 1, i < 8, i <= 7 등도 가능.
a[i++] = n % 2;
n /= 2;
}
for(i = 7; i >= 0; i--){
System.out.printf("%d", a[i]);
}
}
}
출력값
00001010
-----
class Parent {
int compute(int num){
if (num <= 1)
return num;
return compute(num - 1) + compute(num - 2);
}
}
class Child extends Parent {
int compute(int num){
if(num <= 1)
return num;
return compute(num - 1) + compute(num - 3);
}
}
public class Groomgroom {
public static void main(String[] args){
Parent obj = new Child();
System.out.print(obj.compute(4));
}
}
결과 1
https://www.youtube.com/watch?v=TCwfzag23G8&list=PLz95GL3y9Hv0fbwTxWqc3dni3hCA7OXgj&index=8
18번
-----
public class Groomi{
public static void main(String[] args){
int i = 0;
int sum = 0;
while(i < 10){
i++;
if(i % 2 == 1)
continue;
sum +=i;
}
System.out.print(sum);
}
}
답 30
-----
class A {
int a;
public A(int n){
a = n;
}
public void print(){
System.out.println("a="+a);
}
}
class B extends A {
public B(int n){
super(n);
super.print();
}
}
public class Gisafirst {
public static void main(String[] args){
B obj = new B(10);
}
}
답은 a=10
->
선언 방법: public 클래스명(매개변수){...}
-----
/* import java.util.*; */
public class Gisafirst {
static int nSize = 4;
public static void main(String[] args) {
int[] arr = new int[nSize];
makeArray(arr);
for(int i = 0; i < nSize; i++){
System.out.print(arr[i] + " ");
}
}
public static void makeArray(int [] arr) {
for(int i = 0; i < nSize; i++){
arr[i] = i;
}
}
}
결과 0 1 2 3
-----
class Parent {
public void print(){
System.out.println("Parent");
}
}
class Child extends Parent {
public void print() {
System.out.println("Child");
}
}
public class Gisafirst {
public static void main(String[] args){
Parent pa = new Child();
pa.print();
}
}
결과 Child
-----
추상 클래스 -----
추상 클래스 (Abstract class) -> 미완성 설계도
클래스들의 공토오디는 필드와 메소드를 정의한 구체적이지 않은 클래스
상위 클래스에는 메소드의 시근니쳐만 정의해 놓고 그 메소드의 실제 동작 방법은 이 메소드를 상속받은 하위 클래스의 책임으로 위임한다.
형식 abstract class 클래스명 {
,,,,
}
추상 클래스 객체는 생성할 수 없다. -> 실체성이 없고 구체적이지 않으므로.
추상 클래스와 실체 클래스는 상속 관계(extends)를 가진다.
-----
class -----
public class Cat {
// 멤버 변수(인스턴스 변수)
String name;
int age;
String color;
// 생성자(Constructor)
public Cat(String name, int age, String color) {
this.name = name;
this.age = age;
this.color = color;
}
// 메서드(Method)
public void meow() {
System.out.println("냐옹");
}
// Getter 메서드
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getColor() {
return color;
}
// Setter 메서드
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setColor(String color) {
this.color = color;
}
}
멤버 변수(인스턴스 변수): 객체의 특성을 나타내는 변수입니다. 이 클래스에서는 고양이의 이름, 나이, 색깔이며, 이 변수들은 객체가 생성될 때 초기화됩니다.
생성자(Constructor): 객체를 생성할 때 호출되는 메서드입니다. 이 클래스에서는 이름, 나이, 색깔을 인자로 받아 객체를 초기화합니다.
메서드(Method): 객체의 동작을 정의하는 메서드입니다. 이 클래스에서는 "냐옹" 소리를 내는 meow() 메서드가 있습니다.
Getter 메서드: 멤버 변수의 값을 반환하는 메서드입니다. 이 클래스에서는 getName(), getAge(), getColor() 메서드가 있습니다.
Setter 메서드: 멤버 변수의 값을 설정하는 메서드입니다. 이 클래스에서는 setName(), setAge(), setColor() 메서드가 있습니다.
자바에서 클래스는 객체 지향 프로그래밍의 기본적인 개념 중 하나입니다.
클래스는 프로그램에서 사용될 객체의 틀을 정의하며, 객체를 생성하기 위한 설계도 역할을 합니다.
클래스는 여러 가지 멤버 변수와 메서드를 포함하며, 이들을 적절히 구성하여 객체의 동작을 정의합니다.
자바에서 클래스를 사용하는 이유는 다음과 같습니다.
코드의 재사용성 : 클래스를 사용하면 유사한 기능을 하는 코드를 여러 곳에서 쉽게 재사용할 수 있습니다. 클래스를 이용하여 작성된 코드를 다른 프로그램에서도 활용할 수 있어 개발 시간을 단축시키고 코드의
일관성을 유지할 수 있습니다.
유지보수성의 향상 : 클래스를 사용하면 관련 있는 코드를 논리적으로 그룹화하여 구조적으로 정리할 수 있습니다. 이렇게 구조화된 코드는 유지보수가 쉬워집니다. 즉, 클래스를 사용하면 코드의 가독성과 유지보수성이
향상됩니다.
코드의 안정성 : 각 클래스는 자체적으로 캡슐화되어 있어 다른 클래스와 독립적으로 작동합니다. 클래스는 자신의 메서드와 속성만을 외부에서 접근할 수 있게 제한할 수 있기 때문에, 코드의 안정성이 향상됩니다.
-----
main 함수(메서드) -----
JVM(Java Virtual Machine)이 프로그램을 실행할 때 가장 먼저 호출하는 필수 시작점입니다. public static void main(String[] args) 구조를 가지며, 객체 생성
없이 실행되고 프로그램의 전체 흐름을 제어하는 진입점 역할을 합니다.주요 특징 및 의미프로그램 시작점: main 메서드가 없으면 자바 어플리케이션은 실행되지 않습니다.JVM에 의한 호출: 프로그램 실행 시
JVM은 제일 먼저 이 메서드를 찾아 실행합니다.public: 외부(JVM)에서 어디서든 호출 가능해야 하므로 접근 제한자가 public입니다.static: 객체를 생성하지 않아도 메모리에 올라가, JVM이
인스턴스화 없이 바로 호출할 수 있습니다.void: 실행 후 종료 시 호출자(JVM)에게 반환할 값이 없음을 의미합니다.String[] args: 실행 시 외부에서 매개변수(인자)를 받을 수 있는 문자열
배열입니다.
-----
new -----
키워드는 힙(Heap) 메모리 영역에 새로운 배열 객체를 생성하라는 핵심적인 지시어입니다.
생성자(Constructor): new 연산자를 통해서 객체를 생성할 때 반드시 호출이 되고 제일 먼저 실행되는 일종의 메소드
-----
public -----
접근 제한자(Access Modifier)의 일종으로, 클래스, 메서드, 변수를 어디서든(같은 패키지, 다른 패키지, 외부 클래스 등) 자유롭게 접근할 수 있도록 완전 공개하는 것을 의미합니다. 패키지 제한
없이 사용 가능하므로 주로 외부로 노출되어야 하는 API나 메서드에 사용됩니다.
-----
static -----
"클래스에 소속된", "공통적인", "정적인"이라는 의미를 가지며, 인스턴스(객체)를 생성하지 않고도 클래스 이름으로 멤버(변수/메소드)에 바로 접근할 수 있게 합니다. 프로그램 시작 시 메모리(Static
영역)에 고정되어 프로그램 종료 시까지 유지되며, 모든 인스턴스가 하나의 값을 공유합니다
-----
super -----
상위 클래스를 호출하는 예약어
-----
void -----
메서드의 반환 타입(Return Type) 자리에 위치하여, 해당 메서드가 호출된 곳으로 어떤 값도 반환하지 않음을 의미하는 키워드입니다. 메서드가 작업을 수행한 후 결과값을 돌려줄 필요가 없을 때 사용하며,
return 문을 생략하거나 return;으로 종료할 수 있습니다.
-----
public class Groomi {
public static void main(String []args){
int a[][] = {{45, 50, 75}, {89}};
System.out.println(a[0].length);
System.out.println(a[1].length);
System.out.println(a[0][0]);
System.out.println(a[0][1]);
System.out.println(a[1][0]);
}
}
답안: 3
1
45
50
89
-----
https://www.youtube.com/watch?v=xK3UlibfjaM&list=PLz95GL3y9Hv0fbwTxWqc3dni3hCA7OXgj&index=11
34분 24초 17번
-----
public class FirstGroomi {
public static void printPart(String text, String stTwo){
System.out.println(stTwo);
System.out.println(text);
System.out.println(text);
}
public static String groomi(){
return "구름이";
}
public static int inout(){
return 11;
}
public static String groomiTwo(String grootext, String delimiter){
String outPart = "";
outPart = outPart + delimiter + "\n";
outPart = outPart + grootext + "\n";
outPart = outPart + grootext + "\n";
return outPart;
}
public static void main(String[] args){
System.out.println(groomi());
System.out.println(groomiTwo("기임구름", "kimgoorem"));
System.out.println(inout());
printPart("구름", "김");
printPart("구름", "김씨");
printPart("김김", "구름");
//Email.send("groomgroom@groom.com", "Math floor", Math.floor(1.1));
System.out.println("Hello Method");
System.out.println(Math.floor(1.1));
}
}
/*
public static void (String text, String delimiter) throw I0Exception
FileWirter fw = new FileWriter("output.txt");
fw.write(delimiter + "\n");
fw.write(text + "\n");
fw.write(text + "\n");
fw.close();
*/
-----
정보처리기사 실기 java 부분에서 ------------
Parent obj = new Child()
하위 클래스 생성자로 객체 변수를 생성하고, 자료형은 상위 클래스로 지정.
-> 오버라이딩.
System.out.print(obj.compute(4));
obj 객체의 getName() 함수 호출
오버라이딩: 하위 클래스에서 상위 클래스의 메소드를 재정의하는 과정. 오버라이딩 메소드는 부모 클래스 메소드보다 우선 순위가 높음.
int compute(int num)
compute() 함수 실행 num = 4
if (num <= 1)
if ( 4 <= 1) -> FALSE
return compute(num - 1) + compute(num - 3)
return compute(3) + compute(1)
compute() 함수 호출 -> 재귀 함수
------------
public class FirstGroomi {
public static void printPart(String text, String stTwo){
System.out.println(stTwo);
System.out.println(text);
System.out.println(text);
}
public static String groomi(){
return "구름이";
}
public static int inout(){
return 11;
}
public static String groomiTwo(String grootext, String delimiter){
String outPart = "";
outPart = outPart + delimiter + "\n";
outPart = outPart + grootext + "\n";
outPart = outPart + grootext + "\n";
return outPart;
}
public static void main(String[] args){
System.out.println(groomi());
System.out.println(groomiTwo("기임구름", "kimgoorem"));
System.out.println(inout());
printPart("구름", "김");
printPart("구름", "김씨");
printPart("김김", "구름");
//Email.send("groomgroom@groom.com", "Math floor", Math.floor(1.1));
System.out.println("Hello Method");
System.out.println(Math.floor(1.1));
}
}
/*
public static void (String text, String delimiter) throw I0Exception
FileWirter fw = new FileWriter("output.txt");
fw.write(delimiter + "\n");
fw.write(text + "\n");
fw.write(text + "\n");
fw.close();
*/
https://www.youtube.com/watch?v=xK3UlibfjaM&list=PLz95GL3y9Hv0fbwTxWqc3dni3hCA7OXgj&index=11
17번 34분 6초
-------
package javas;
public class javas {
public static void main(String[] args) {
System.out.println("1 ~ 10 = " + calcSum(1, 10));
System.out.println("2 ~ 10 = " + calcSum(2, 10));
}
static int calcSum(int from, int to) {
int sum = 0;
for(int i = from; i <= to; i++) {
sum += i;
}
return sum;
}
}
-------
package javas;
public class javas {
public static void main(String[] args) {
int year = 2026;
int month = 12;
int days = getMonthDays(year, month);
System.out.println(year + "년도" + month + "월은" + days + "일까지 이다.");
}
static int getMonthDays(int year, int month) {
int[] arDays = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if(month == 2) {
if((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
return 29;
}
return 28;
} else {
return arDays[month];
}
}
}
-------
#####
import java.time.LocalDate;
package javas;
public class javas {
public static void main(String[] args) {
System.out.println("오늘은 " + getDate() + "일입니다.");
}
static int getDate() {
java.time.LocalDate today = java.time.LocalDate.now();
int day = today.getDayOfMonth();
return day;
}
}
------
package javas;
public class javas {
public static void main(String[] args) {
System.out.println("1 ~ 10 = " + calcSum(1, 10));
System.out.println("1 ~ 10 = " + calcSum(15, 100));
}
static int calcSum(int from, int to) {
if (from > to) {
return 0;
}
int sum = 0;
for (int i = from; i <= to; i++) {
sum += i;
}
return sum;
}
}
----------------------------
package javas;
public class javas {
public static void main(String[] args) {
printSum(1, 10);
printSum(15, 100);
}
static void printSum(int from, int to) {
int sum = 0;
for (int i = from; i <= to; i++) {
sum += i;
}
System.out.println(from + "~" + to + "=" + sum);
}
}
----------------------------
package java_prac;
public class prac {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
outStar(i);
System.out.println();
}
}
static void outStar(int num) {
for (int i = 0; i < num; i++) {
System.out.print("공부합시다");
}
}
}
--------------
package java_prac;
public class prac {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
outStar(" ", 10 - i);
//전각 공백 (ㄱ + 한자 + 1번)
outStar("공부", i);
System.out.println();
}
}
static void outStar(String ch, int num) {
for (int i = 0; i < num; i++) {
System.out.print(ch);
}
}
}
---------------
package java_prac;
public class prac {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
outStar(" ", 10 - i, false);
//전각 공백 (ㄱ + 한자 + 1번)
outStar("공부", i, true);
}
}
static void outStar(String ch, int num, boolean newLine) {
for (int i = 0; i < num; i++) {
System.out.print(ch);
}
if (newLine) {
System.out.println();
}
}
}
-------
import java.util.*;
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
outChars(' ', 10-i);
outCharsln('*', i);
}
}
static void outChars(char ch, int num){
for (int i = 0; i < num; i++) {
System.out.print(ch);
}
}
static void outCharsln(char ch, int num) {
outChars(ch, num);
System.out.println();
}
}
--------------------------------
class GroomiString {
public static void main(String[] args){
outCharsln('김', 5 + 4);
System.out.println("구름이");
outCharsln('김', 5 + 4);
}
static void outChars(char ch, int num){
for (int i = 0; i < num; i++){
System.out.print(ch);
}
}
static void outCharsln(char ch, int num){
outChars(ch, num);
System.out.println();
}
}
----------------------
class GroomiString {
public static void main(String[] args){
String str = "김구름";
String result = str.repeat(3);
//repeat는 문자열을 횟수만큼 반복 출력하는거.
System.out.println(result);
}
}
-----------------------
class GroomiString {
public static void main(String[] args){
outBox("김구름");
outBox("김구름구름구름멍멍멍");
}
static void outBox(String message){
outCharsln('-', message.length() + 4);
System.out.println("구름" + message + "구름");
outCharsln('-', message.length() + 4);
}
static void outChars(char ch, int num){
for (int i = 0; i < num; i++){
System.out.print(ch);
}
}
static void outCharsln(char ch, int num){
outChars(ch, num);
System.out.println();
}
}
---------
class Groomgroomi{
public static void main(String[] args){
int num = 4;
getDouble(num);
//num에다가 위 함수를 대입 안해줘서 값이 그대로 4가 출력됨.
//num = getDouble(num);
System.out.println("num = " + num);
}
static int getDouble(int value){
value *= 2;
return value;
}
}
---------------------
class Groomjava {
public static void main(String[] args){
int[] num = {2, 4, 6};
getDouble(num);
System.out.println(num[0]);
}
static void getDouble(int[] value) {
value[0] *= 2;
}
}
/* #####
class Groomjava {
public static void main(String[] args){
int[] num = {2, 4, 6};
int num2 = getDouble(num);
System.out.println(num2);
}
static void getDouble(int[] vlaue) {
value[0] *= 2;
}
}
*/
------------------------
import java.util.*;
public class Main {
public static void main(String[] args) {
System.out.println(getSum(1, 2));
System.out.println(getSum(1, 2, 3, 4));
System.out.println(getSum(8, 9, 6, 2, 9));
}
static int getSum(int... a){
int sum = 0;
for (int i : a) {
sum += i;
}
return sum;
}
}
---------------
import java.util.*;
public class Main {
public static void main(String[] args) {
System.out.println(getSum(1, 2));
System.out.println(getSum(1, 2, 3, 4));
System.out.println(getSum(8, 9, 6, 2, 9));
}
static int getSum(int... a){
/*
int... a는 가변 인자(Variable Arguments, Varargs)를 의미하며, 해당 메서드가 int 타입의 인자를 0개부터 여러 개(개수 제한 없이) 받을 수 있다는 뜻입니다. 내부적으로는 int[] a 배열로 처리되어, 메서드 내부에서 배열처럼 사용할 수 있습니다.
*/
int sum = 0;
for (int i : a) {
/*
for (int i : a)는 향상된 for문(Enhanced for loop, for-each문)이라 불리며, 배열이나 컬렉션(a)의 요소를 처음부터 끝까지 하나씩 꺼내어 변수(i)에 담아 반복 처리하는 구문입니다. 인덱스(\(i\))를 직접 관리하지 않아도 되어 코드가 간결하고 안전하다는 장점이 있습니다.
*/
sum += i;
}
return sum;
}
}
----------------
import java.util.*;
public class Main {
public static void main(String[] args) {
System.out.println("[3, 5] = " + getMax(3, 5));
}
static int getMax(int a, int b){
if (a > b) {
return a;
} else {
return b;
}
}
}
---------------------
파일명 -> Groompart.java
class Groom {
String dogname;
boolean gansik;
void run(){
if(gansik){
System.out.println("간식이 좋아요");
} else {
System.out.println("간식 먹기 싫어요");
}
}
void stop(){
System.out.println(dogname + " 멍멍이");
}
}
class Groompart {
public static void main(String[] args){
Groom groomi = new Groom();
groomi.dogname = "김구름";
groomi.gansik = true;
groomi.run();
groomi.stop();
}
}
-----------------
파일명 -> Groompart.java
class Groom {
String dogname;
boolean gansik;
void run(){
if(gansik){
System.out.println("간식이 좋아요");
} else {
System.out.println("간식 먹기 싫어요");
}
}
void stop(){
System.out.println(dogname + " 멍멍이");
}
}
class Groompart {
public static void main(String[] args){
Groom groomi = new Groom();
groomi.dogname = "김구름";
groomi.gansik = true;
groomi.run();
groomi.stop();
Groom guumi = new Groom();
guumi.dogname = "굴흠이";
guumi.gansik = false;
guumi.run();
guumi.stop();
}
}
---------------------
class Outer {
public static void main(String[] args){
Time now = new Time();
now.am = true;
now.hour = 12;
now.minute = 34;
now.second = 56;
now.whatTime();
}
}
class Time {
boolean am;
int hour;
int minute;
int second;
void whatTime() {
System.out.print(am ? "오전 " : "오후 ");
System.out.print(hour + "시 " + minute + "분 " + second + "초 ");
}
}
-----------------------
https://dev.java/learn/language-basics/
자바 언어 기초부터 보기.
https://dev.java/learn/
------