[JAVA] 개념정리 및 문제풀이

장성욱·2025년 7월 7일

JAVA

목록 보기
20/23

배열

같은 자료형의 값들을 순차적으로 저장하는 크기가 고정적인 자료 구조

  • 크기는 변경 불가

  • 인덱스 0부터 시작

  • 한가지 타입만 저장 가능

  • 여러 개의 데이터를 한 번에 저장하며 빠른 접근이 가능

  • 코드의 가독성과 유지보수성 향상

숫자 10개를 입력받고 배열에 저장 뒤 출력 프로그램

import java.util.Scanner;
class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int[] arr = new int[10];

    for (int i = 0; i < 10; i ++) {
      System.out.printf("%d번째 숫자 : ", i + 1);
      arr[i] = sc.nextInt();
      sc.nextLine();
    }
    for (int i = 0; i < 10; i ++) {
      System.out.printf("%d번째 숫자 : %d\n", i +1, arr[i]);
    }
  }
}

배열에서 최소값 최대값 구하기


class Main {
  public static void main(String[] args) {
    int[] arr = new int[5];
    arr[0] = 1;
    arr[1] = 3;
    arr[2] = 2;
    arr[3] = 8;
    arr[4] = 9;
    
    // int[] arr = {1,3,2,8,9}; 와도 같음

    int min = arr[0];
    int max = arr[0];

    for (int i = 0; i < arr.length; i ++) {
      if (min > arr[i]) {
        min = arr[i];
      }
      if (max < arr[i]) {
        max = arr[i];
      }
    }
    System.out.println("최대값 : " + max + "\n최소값 : " + min);
  }
}

배열 모든 값들의 평균 구하기

class Main {
  public static void main(String[] args) {
    int arr[] = {2,5,1,8,6};
    int s = 0;

    for (int i = 0; i < arr.length; i ++) {
      s += arr[i];
    }
    System.out.println("평균 : " + s/arr.length);
  }
}

클래스

  • 클래스와 객체의 차이
    클래스는 객체(인스턴스)를 만들기 위한 설계도이고,
    객체는 설계도(클래스)의 정의로 만들어진 제품

  • 클래스의 구성 요소

  1. 속성 : 클래스의 포함된 변수로 객체의 데이터를 저장
  2. 메서드 : 클래스 내 함수로 객체의 기능을 정의
  3. 생성자 : 객체를 만들 때 호출되는 특별한 함수

Car 클래스를 정의하고, 속성(모델, 색상, 연식)과 메서드(정보 출력)를 구현

class Main {
  public static void main(String[] args) {
    Car kia = new Car("k5", "white", 2025);
    kia.introduce();
  }
}
class Car {
  String model;
  String color;
  int year;

  Car(String model, String color, int year) {
    this.model = model;
    this.color = color;
    this.year = year;
  }

  void introduce () {
    System.out.println("모델명 : " + model + "\n색상 : " + color + "\n연식 : " + year);
  }
}

Student 클래스를 정의하고, 학생의 이름과 점수를 입력받아 평균 점수를 계산하는 프로그램


class Main {
  public static void main(String[] args) {
    Student jsw = new Student("장성욱",95,88);
    jsw.avg();
  }
}
class Student {
  String name;
  int korean_score;
  int math_score;

  Student(String name, int korean_score, int math_score) {
    this.name = name;
    this.korean_score = korean_score;
    this.math_score = math_score;
  }

  void avg () {
    System.out.println("이름 : " + name + "\n국어 : " + korean_score + "점" + "\n수학 : " + math_score + "점\n평균 : " + (korean_score + math_score) /2 + "점");
  }
}

은행 계좌를 나타내는 BankAccount 클래스를 정의하고, 입금과 출금 기능을 구현

class Main{
  public static void main(String[] args) {
    BankAccount ba = new BankAccount("카카오뱅크", 123456123, 56000);
    ba.입금(25000);
  }
}
class BankAccount {
  String bank;
  int account_num;
  int able;

  BankAccount(String bank, int account_num, int able) {
    this.bank = bank;
    this.account_num = account_num;
    this.able = able;
  }

  void 입금(int 입금금액) {
    System.out.println(bank + " " +account_num + "\n" + 입금금액 + "원이 입금 되었습니다." );
  }
  void 출금(int 출금금액) {
    System.out.println(bank + " " +account_num + "\n" + 출금금액 + "원이 입금 되었습니다." );
  }
}

상속

  • 상속의 개념
    부모클래스에 정의된 속성, 메섣, 생성자 등의 기능을 자식클래스가 물려받아 사용하는 것

  • 상속의 장점

  1. 공통된 기능을 부모클래스에 정의해 중복 없이 사용해 가독성이 높아짐
  2. 수정이 필요한 경우 부모클래스만 수정하면 됨
  3. 물려받는 것과 별도로 자식클래스 고유의 기능도 추가 가능
  • super의 역할
    자식클래스에서 부모클래스의 속성, 메서드, 생성자에 접근하게 해줌
  1. super() : 부모클래스 생성자 호출 // super(name,age)
  2. super.속성 or 메서드 : 부모클래스 속성, 메서드에 접근 // super.name, super.cry()..

생성자를 생성했다면 객체 생성 시 인자에 속성값 꼭 적어주기!!

Animal 클래스를 정의하고, 이를 상속받는 Dog와 Cat 클래스를 정의하여 각 동물의 소리를 출력하는 프로그램

class Main {
  public static void main(String[] args) {
    Dog d = new Dog("흰둥이", "멍멍");
    Cat c = new Cat("야옹이", "야옹");

    d.짖다();
    c.짖다();
  }
}
class Animal {
  String name;
  String crying;

  Animal(String name, String crying) {
    this.name = name;
    this.crying = crying;
  }

  void 짖다 () {
    System.out.println(name + "가 " + crying + " 짖는다.");
  }
}
class Dog extends Animal {
  Dog(String name, String crying) {
    super(name, crying);
  }
}
class Cat extends Animal {
  Cat(String name, String crying) {
    super(name, crying);
  }
}

Person 클래스를 정의하고, 이를 상속받는 Student와 Teacher 클래스를 정의하여 각각의 정보 출력 메서드를 구현

class Main{
  public static void main(String[] args) {
    Student st = new Student("톰", 19, "학생");
    Teacher tc = new Teacher("존", 33, "선생");

    st.introduce();
    tc.introduce();
  }
}
class Person {
  String name;
  int age;
  String job;

  Person(String name, int age, String job) {
    this.name = name;
    this.age = age;
    this.job = job;
  }
  void introduce () {
    System.out.println("이름 : " + name + "\n나이 : " + age + "\n직업 : " + job);
  }
}
class Student extends Person {
  Student (String name, int age, String job) {
    super(name, age, job);
  }
}
class Teacher extends Person {
  Teacher (String name, int age, String job) {
    super(name, age, job);
  }
}

Vehicle 클래스를 정의하고, 상속받는 Car와 Bike 클래스를 만들어 정보를 출력하는 프로그램을 작성

class Main {
  public static void main(String[] args) {
    Car c = new Car("기아","k5", 150);
    Bike b = new Bike("삼천리", "자전거", 25);

    c.introduce();
    b.introduce();
  }
}
class Vehicle {
  String brand;
  String model;
  int speed;

  Vehicle(String brand, String model, int speed) {
    this.brand = brand;
    this.model = model;
    this.speed = speed;
  }
  void introduce() {
    System.out.println(brand + " " + model+ "이 최고속도 " +  speed + "km로 달립니다.");
  }
}
class Car extends Vehicle {
  Car(String name, String model, int speed) {
    super(name, model, speed);
    }
  }

class Bike extends Vehicle {
  Bike(String name, String model, int speed) {
    super(name, model, speed);
  }

}
profile
https://frost-puck-b0f.notion.site/B-2610fdaef71d80c49d1bccdcb575dcb5

0개의 댓글