[개발] 프로그램 지식

[JAVA] 자바 메서드, 클래스 이론 정리 (1)

  • -
반응형

출처  : https://www.w3schools.com/java

JAVA 메서드

메서드 오버로딩
메서디 오버로딩을 사용하면 여러 메소드가 서로 다른 매개변수를 사용하여 동일한 이름을 가질 수 있습니다.

자바 재귀
재귀는 함수 자체를 호출하는 기술입니다.
public class Main {
  public static void main(String[] args) {
    int result = sum(10);
    System.out.println(result);
  }
  public static int sum(int k) {
    if (k > 0) {
      return k + sum(k - 1);
    } else {
      return 0;
    }
  }
}

 

 



정지상태
루프가 무한 루프 문제에 직면할 수 있는 것처럼 재귀 함수도 무한 재귀 문제에 직면할 수 있습니다. 무한 재귀는 함수가 자신을 호출하는 것을 멈추지 않는 경우입니다. 모든 재귀 함수에는 함수가 자신을 호출하는 것을 멈추는 조건인 정지 조건이 있어야 합니다. 이전 예에서 정지 조건은 매개변수가 k0이 되는 경우입니다.

다양한 예시를 통해 개념을 이해하는데 도움이 됩니다. 이 예에서 함수는 시작과 끝 사이에 숫자 범위를 추가합니다. 이 재귀 함수의 정지 조건은 end가 start 보다 크지 않은 경우입니다 .
public class Main {
  public static void main(String[] args) {
    int result = sum(5, 10);
    System.out.println(result);
  }
  public static int sum(int start, int end) {
    if (end > start) {
      return end + sum(start, end - 1);
    } else {
      return end;
    }
  }
}

 

 

 



-- 자바 클래스 이론 START --

자바 - OOP란 무엇인가?
OOP는 객체 지향 프로그래밍을 의미합니다 .

절차적 프로그래밍은 데이터에 대한 작업을 수행하는 절차나 메서드를 작성하는 반면, 객체 지향 프로그래밍은 데이터와 메서드를 모두 포함하는 개체를 만드는 것입니다.

객체 지향 프로그래밍은 절차적 프로그래밍에 비해 몇 가지 장점이 있습니다.

OOP는 더 빠르고 실행하기 쉽습니다.
OOP는 프로그램에 대한 명확한 구조를 제공합니다.
OOP는 Java 코드를 "반복하지 마십시오"를 DRY로 유지하고 코드를 더 쉽게 유지 관리, 수정 및 디버깅할 수 있도록 해줍니다.
OOP를 사용하면 더 적은 코드와 더 짧은 개발 시간으로 완전히 재사용 가능한 애플리케이션을 만들 수 있습니다.
팁: "DRY(반복하지 마십시오)" 원칙은 코드 반복을 줄이는 것입니다. 애플리케이션에 공통된 코드를 추출하여 반복하지 않고 한 곳에 배치하여 재사용해야 합니다.

 

 

 

 


Java 클래스/객체 [ Class / Objects ] 
Java는 객체 지향 프로그래밍 언어입니다.

Java의 모든 것은 해당 속성 및 메소드와 함께 클래스 및 객체와 연관되어 있습니다. 예를 들어 실생활에서 자동차는 객체입니다. 자동차에는 무게, 색상과 같은 속성 과 구동 및 브레이크와 같은 방법이 있습니다.
클래스는 객체 생성자 또는 객체 생성을 위한 "청사진"과 같습니다.

 

 


객체 생성
Java에서는 클래스에서 객체가 생성됩니다. 우리는 이미 라는 클래스를 생성했으므로 Main이제 이를 사용하여 객체를 생성할 수 있습니다.

public class Main {
  int x = 5;

  public static void main(String[] args) {
    Main myObj = new Main();
    System.out.println(myObj.x);
  }
}

 

 

 

 

 

Java 클래스 속성 [ Attribtue, Field ]
이전 장에서는 x예제에서 "변수"라는 용어를 사용했습니다(아래 참조). 실제로는 클래스의 속성 입니다 . 또는 클래스 속성이 클래스 내의 변수라고 말할 수도 있습니다.
클래스 속성의 또 다른 용어는 필드 입니다 .

 

 

 


static / public 

static : 객체의 인스턴스화 없이 사용 / 유틸리티 함수, 공유 데이터, 상수 등을 정의할 때 사용

public class Main {
  // Static method
  static void myStaticMethod() {
    System.out.println("Static methods can be called without creating objects");
  }

  // Public method
  public void myPublicMethod() {
    System.out.println("Public methods must be called by creating objects");
  }

  // Main method
  public static void main(String[] args) {
    myStaticMethod(); // Call the static method  -- static은 객체의 인스턴스화 없이 사용   
  // myPublicMethod(); This would compile an error

    Main myObj = new Main(); // Create an object of Main
    myObj.myPublicMethod(); // Call the public method on the object
  }
}

점( .)은 객체의 속성과 메소드에 액세스하는 데 사용됩니다.
Java에서 메소드를 호출하려면 메소드 이름, 괄호 () , 세미콜론( ;)을 차례로 작성합니다.
클래스에는 일치하는 파일 이름( Main및 Main.java )이 있어야 합니다.


 

 

 


자바 생성자 Constructors
Java의 생성자는 객체를 초기화하는 데 사용되는 특수 메서드 입니다. 생성자는 클래스의 객체가 생성될 때 호출됩니다. 객체 속성의 초기 값을 설정하는 데 사용할 수 있습니다.

 

 

 

 


자바 수정자 Modifiers
액세스 수정자 - 액세스 수준을 제어합니다.
비액세스 수정자 - 액세스 수준을 제어하지 않지만 다른 기능을 제공합니다.

 


액세스 수정자
1)
클래스 의 경우 public또는 default를 사용할 수 있습니다 .
public : The class is accessible by any other class
default : The class is only accessible by classes in the same package. This is used when you don't specify a modifier. You will learn more about packages in the Packages chapter

public: 이 클래스는 다른 모든 클래스에서 접근할 수 있습니다.
default: 이 클래스는 동일한 패키지 내의 클래스에서만 접근할 수 있습니다. 이는 접근 제한자를 지정하지 않은 경우에 사용됩니다. 패키지에 대해 더 자세히 배우는 것은 "패키지" 장에서 설명합니다.

2) 
속성, 메소드 및 생성자 의 경우 다음 중 하나를 사용할 수 있습니다.
public : The code is accessible for all classes
private : The code is only accessible within the declared class
default : The code is only accessible in the same package. This is used when you don't specify a modifier. You will learn more about packages in the Packages chapter
protected : The code is accessible in the same package and subclasses. You will learn more about subclasses and superclasses in the Inheritance chapter

public: 해당 코드는 모든 클래스에서 접근할 수 있습니다.
private: 해당 코드는 선언된 클래스 내에서만 접근할 수 있습니다.
default: 해당 코드는 동일한 패키지 내에서만 접근할 수 있습니다. 이는 접근 제한자를 지정하지 않은 경우에 사용됩니다. 패키지에 대해 더 자세히 알아보는 것은 "패키지" 장에서 설명됩니다.
protected: 해당 코드는 동일한 패키지 내에서 및 하위 클래스에서 접근할 수 있습니다. 하위 클래스와 상위 클래스에 대해 더 자세히 알아보는 것은 "상속" 장에서 설명됩니다.

 


/

 


비액세스 수정자
1)
클래스 의 경우 final다음 중 하나를 사용할 수 있습니다 abstract.
final : The class cannot be inherited by other classes (You will learn more about inheritance in the Inheritance chapter)
abstract : The class cannot be used to create objects (To access an abstract class, it must be inherited from another class. You will learn more about inheritance and abstraction in the Inheritance and Abstraction chapters)

final: 해당 클래스는 다른 클래스에서 상속될 수 없습니다. (상속에 대해는 "상속" 장에서 더 자세히 배우게 됩니다.)
abstract: 해당 클래스는 객체를 생성하는 데 사용할 수 없습니다. 

2) 
속성 및 메소드 의 경우 다음 중 하나를 사용할 수 있습니다.
final : Attributes and methods cannot be overridden/modified
static : Attributes and methods belongs to the class, rather than an object
abstract : Can only be used in an abstract class, and can only be used on methods. The method does not have a body, for example abstract void run();. The body is provided by the subclass (inherited from). You will learn more about inheritance and abstraction in the Inheritance and Abstraction chapters
transient : Attributes and methods are skipped when serializing the object containing them
synchronized : Methods can only be accessed by one thread at a time
volatile : The value of an attribute is not cached thread-locally, and is always read from the "main memory"

final: 속성 및 메서드를 오버라이드(재정의)하거나 수정할 수 없습니다.
static: 속성 및 메서드는 객체가 아닌 클래스에 속합니다.
abstract: 추상 클래스에서만 사용할 수 있으며 메서드에만 사용됩니다. 메서드에는 본문이 없으며, 예를 들어 abstract void run();처럼 정의됩니다. 본문은 하위 클래스에서 제공됩니다(상속됨). 상속과 추상화에 대해 더 자세히 알아보게 됩니다.
transient: 속성 및 메서드는 해당 객체를 직렬화할 때 건너뜁니다.
synchronized: 메서드는 한 번에 하나의 스레드만 접근할 수 있습니다.
volatile: 속성의 값은 스레드 내부에 캐시되지 않으며 항상 "main memory"에서 읽힙니다.

 

 



자바 캡슐화 Encapsulation
캡슐화 의 의미는 "민감한" 데이터가 사용자에게 숨겨지도록 하는 것입니다. 이를 달성하려면 다음을 수행해야 합니다.
클래스 변수/속성을 다음과 같이 선언합니다. private
변수 값에 액세스하고 업데이트하기 위한 공개 get 및 set 메소드 제공

public class Person {
  private String name; // private = restricted access

  // Getter
  public String getName() {
    return name;
  }

  // Setter
  public void setName(String newName) {
    this.name = newName;
  }
}

 

 


왜 캡슐화하는가?
클래스 속성 및 메소드에 대한 더 나은 제어
클래스 속성은 읽기 전용 (메서드만 사용하는 경우 get) 또는 쓰기 전용 (메서드만 사용하는 경우 set) 으로 설정할 수 있습니다.
유연성: 프로그래머는 다른 부분에 영향을 주지 않고 코드의 한 부분을 변경할 수 있습니다.
데이터 보안 강화


 

 


자바 패키지 Packages / API
Java의 패키지는 관련 클래스를 그룹화하는 데 사용됩니다. 파일 디렉토리의 폴더 로 생각하십시오 . 우리는 이름 충돌을 피하고 더 나은 유지 관리가 가능한 코드를 작성하기 위해 패키지를 사용합니다. 패키지는 두 가지 범주로 나뉩니다.

내장 패키지(Java API의 패키지)
사용자 정의 패키지(자신만의 패키지 생성)

 

 


내장 패키지
Java API는 Java 개발 환경에 포함되어 무료로 사용할 수 있는 미리 작성된 클래스 라이브러리입니다.
라이브러리에는 입력 관리, 데이터베이스 프로그래밍 등을 위한 구성 요소가 포함되어 있습니다. 전체 목록은 Oracle 웹사이트( https://docs.oracle.com/javase/8/docs/api/ )에서 확인할 수 있습니다 .
라이브러리는 패키지 와 클래스 로 구분됩니다 . 즉, 단일 클래스(메소드 및 속성과 함께)를 가져오거나 지정된 패키지에 속하는 모든 클래스를 포함하는 전체 패키지를 가져올 수 있습니다.

패키지 이름은 클래스 이름과 충돌하지 않도록 '''소문자'''로 작성해야 합니다.

 



자바 상속 Inheritance
Java 상속(하위 클래스 및 슈퍼 클래스)
Java에서는 한 클래스에서 다른 클래스로 속성과 메소드를 상속할 수 있습니다. 우리는 "상속 개념"을 두 가지 범주로 분류합니다.

하위 클래스 (자식) - 다른 클래스에서 상속되는 클래스
슈퍼클래스 (부모) - 상속되는 클래스

클래스에서 상속하려면 extends 키워드를 사용하세요.

아래 예에서 클래스(하위 클래스) 는 클래스(슈퍼클래스) Car로부터 속성과 메서드를 상속합니다 .
class Vehicle {
  protected String brand = "Ford";        // Vehicle attribute
  public void honk() {                    // Vehicle method
    System.out.println("Tuut, tuut!");
  }
}

class Car extends Vehicle {
  private String modelName = "Mustang";    // Car attribute
  public static void main(String[] args) {

    // Create a myCar object
    Car myCar = new Car();

    // Call the honk() method (from the Vehicle class) on the myCar object
    myCar.honk();

    // Display the value of the brand attribute (from the Vehicle class) and the value of the modelName from the Car class
    System.out.println(myCar.brand + " " + myCar.modelName);
  }
}


 


자바 다형성 Polymorphism
다형성은 "다양한 형태"를 의미하며 상속을 통해 서로 관련된 클래스가 많을 때 발생합니다.

이전 장에서 지정한 것처럼; 상속을 통해 다른 클래스의 속성과 메서드를 상속받을 수 있습니다. 다형성은 이러한 방법을 사용하여 다양한 작업을 수행합니다. 이를 통해 우리는 단일 작업을 다양한 방식으로 수행할 수 있습니다.

class Animal {
  public void animalSound() {
    System.out.println("The animal makes a sound");
  }
}

class Pig extends Animal {
  public void animalSound() {
    System.out.println("The pig says: wee wee");
  }
}

class Dog extends Animal {
  public void animalSound() {
    System.out.println("The dog says: bow wow");
  }
}

class Main {
  public static void main(String[] args) {
    Animal myAnimal = new Animal();  // Create a Animal object
    Animal myPig = new Pig();  // Create a Pig object
    Animal myDog = new Dog();  // Create a Dog object
    myAnimal.animalSound();
    myPig.animalSound();
    myDog.animalSound();
  }
}



Java 내부 클래스 Inner Classes
Java에서는 클래스(클래스 내의 클래스)를 중첩하는 것도 가능합니다. 중첩 클래스의 목적은 함께 속한 클래스를 그룹화하여 코드를 더 읽기 쉽고 유지 관리하기 쉽게 만드는 것입니다.
class OuterClass {
  int x = 10;

  class InnerClass {
    int y = 5;
  }
}

public class Main {
  public static void main(String[] args) {
    OuterClass myOuter = new OuterClass();
    OuterClass.InnerClass myInner = myOuter.new InnerClass();
    System.out.println(myInner.y + myOuter.x);
  }
}

내부 클래스에서 외부 클래스에 액세스
내부 클래스의 한 가지 장점은 외부 클래스의 속성과 메서드에 액세스할 수 있다는 것입니다.
class OuterClass {
  int x = 10;

  class InnerClass {
    public int myInnerMethod() {
      return x;
    }
  }
}

public class Main {
  public static void main(String[] args) {
    OuterClass myOuter = new OuterClass();
    OuterClass.InnerClass myInner = myOuter.new InnerClass();
    System.out.println(myInner.myInnerMethod());
  }
}

 

 


자바 추상화 Abstraction
데이터 추상화는 특정 세부 정보를 숨기고 필수 정보만 사용자에게 표시하는 프로세스입니다. 추상화는 추상 클래스 나 인터페이스 (다음 장에서 자세히 알아보겠습니다)를 사용하여 달성할 수 있습니다 .

키워드 abstract는 클래스 및 메서드에 사용되는 비액세스 한정자입니다.

추상 클래스: 객체를 생성하는 데 사용할 수 없는 제한된 클래스입니다(액세스하려면 다른 클래스에서 상속되어야 함).
추상 메서드: 추상 클래스에서만 사용할 수 있으며 본문이 없습니다. 본문은 하위 클래스(상속됨)에 의해 제공됩니다.
추상 클래스에는 추상 메서드와 일반 메서드가 모두 있을 수 있습니다.

// Abstract class
abstract class Animal {
  // Abstract method (does not have a body)
  public abstract void animalSound();
  // Regular method
  public void sleep() {
    System.out.println("Zzz");
  }
}

// Subclass (inherit from Animal)
class Pig extends Animal {  ---------- VVVVVV
  public void animalSound() {
    // The body of animalSound() is provided here
    System.out.println("The pig says: wee wee");
  }
}

class Main {
  public static void main(String[] args) {
    Pig myPig = new Pig(); // Create a Pig object
    myPig.animalSound();
    myPig.sleep();
  }
}

 

 

 


자바 인터페이스 Interface
Java에서 추상화를 달성하는 또 다른 방법은 인터페이스를 사용하는 것입니다.
An은 빈 몸체로 관련 메서드를 그룹화하는 데 사용되는 interface완전히 " 추상 클래스 "입니다.
// interface
interface Animal {
  public void animalSound(); // interface method (does not have a body)
  public void run(); // interface method (does not have a body)
}
인터페이스 메서드에 액세스하려면 (implements ) 키워드를 사용하여 다른 클래스에서 인터페이스를 "구현"해야 합니다(상속된 것과 비슷함) extends. 인터페이스 메소드의 본문은 "implement" 클래스에서 제공됩니다.

// Interface
interface Animal {
  public void animalSound(); // interface method (does not have a body)
  public void sleep(); // interface method (does not have a body)
}

// Pig "implements" the Animal interface
class Pig implements Animal {
  public void animalSound() {
    // The body of animalSound() is provided here
    System.out.println("The pig says: wee wee");
  }
  public void sleep() {
    // The body of sleep() is provided here
    System.out.println("Zzz");
  }
}

class Main {
  public static void main(String[] args) {
    Pig myPig = new Pig();  // Create a Pig object
    myPig.animalSound();
    myPig.sleep();
  }
}

 

 


인터페이스에 대한 참고 사항:
추상 클래스 와 마찬가지로 인터페이스는 객체를 생성하는 데 사용할 수 없습니다 (위 예에서는 MyMainClass에서 "동물" 객체를 생성할 수 없습니다).
인터페이스 메소드에는 본문이 없습니다. 본문은 "구현" 클래스에 의해 제공됩니다.
인터페이스 구현 시 해당 메서드를 모두 재정의해야 합니다.
인터페이스 방법은 기본적 abstract으로 public
인터페이스 속성은 기본적 으로 public이며 staticfinal
인터페이스는 생성자를 포함할 수 없습니다(객체를 생성하는 데 사용할 수 없으므로).

 

 


인터페이스를 사용하는 이유와 시기
1) 보안을 달성하려면 - 특정 세부 정보를 숨기고 개체(인터페이스)의 중요한 세부 정보만 표시합니다.
2) Java는 "다중 상속"을 지원하지 않습니다(클래스는 하나의 슈퍼클래스에서만 상속할 수 있음). 그러나 클래스가 여러 인터페이스를 구현할 수 있으므로 인터페이스를 사용하여 이를 달성할 수 있습니다.

다중 인터페이스
여러 인터페이스를 구현하려면 쉼표로 구분하세요.
interface FirstInterface {
  public void myMethod(); // interface method
}

interface SecondInterface {
  public void myOtherMethod(); // interface method
}

class DemoClass implements FirstInterface, SecondInterface { --- VVVVVVVVVV
  public void myMethod() {
    System.out.println("Some text..");
  }
  public void myOtherMethod() {
    System.out.println("Some other text...");
  }
}

class Main {
  public static void main(String[] args) {
    DemoClass myObj = new DemoClass();
    myObj.myMethod();
    myObj.myOtherMethod();
  }
}

 

 

 

 



자바 열거형 Enums / enumerations / "구체적으로 나열됨"을 의미
enum Level {
  LOW,
  MEDIUM,
  HIGH
}

public class Main {
  enum Level {
    LOW,
    MEDIUM,
    HIGH
  }

  public static void main(String[] args) {
    Level myVar = Level.MEDIUM; 
    System.out.println(myVar);
  }
}

열거형을 통한 루프
열거형 유형에는 values()모든 열거형 상수의 배열을 반환하는 메서드가 있습니다. 이 방법은 열거형의 상수를 반복할 때 유용합니다.


for (Level myVar : Level.values()) {
  System.out.println(myVar);
}


반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.