ABOUT ME

Today
Yesterday
Total
  • Java Class
    Java 2024. 9. 7. 23:28

    Java는 모든 것이 Class나 객체와 연관되어있다. 

     

    class 정의:

    modifier class ClassName {
        //attributes
        //constructor
        //methods
    }

    class이름은 모든 단어의 첫 글자를 대문자로 한다.

     

    class를 위한 access modifier는 public과 default가 있다.

    • public - 클래스는 다른 클래스에 의해 접근 가능하다
    • default - 클래스는 같은 패키지 안에 있는 클래스들에 의해서만 접근 가능하다. modifier를 지정하지 않았을 때 사용된다.

    class를 위한 non-access modifier는 final과 abstract가 있다.

    • final - 클래스는 다른 클래스에 의해 상속받아질 수 없다.
    • abstract - 클래스는 객체 생성을 위해 사용될 수 없다. (abstract 클래스에 접근하려면 다른 클래스에 의해 상속받아져야 한다.)

    객체 생성:

    ClassName myObj = new ClassName();

    객체 생성은

    클래스이름 객체이름 = new 클래스생성자();

    로 생성한다.

    1. Attributes (속성)

    속성 정의

    class의 attribute 정의는 

    modifier type attributeName = value;

    로 정의한다.

    public class Main {
      public int x = 5;
      int y = 3;
    }

    속성 이름은 첫 단어의 첫 문자는 소문자, 두번째 단어부터의 첫 문자는 대문자로 한다.

     

    속성 접근

    objName.attributeName으로 속성에 접근한다.

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

    또는 static을 부여해 ClassName.attributeName으로 속성에 접근한다.

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

    속성 변경

    속성 값을 변경할 수 있다.

    public class Main {
        int x = 5;
        public static void main(String[] args) {
            Main obj = new Main();
            obj.x = 10;
            System.out.println(obj.x);
        }
    }

    static 속성 값 변경

    public class Main {
        static int x = 5;
        public static void main(String[] args) {
            Main.x = 10;
            System.out.println(Main.x);
        }
    }

    final modifier를 붙이면 값 변경이 불가능하다.

    public class Main {
        final static int MIN_WIDTH = 5;
        public static void main(String[] args) {
            Main.MIN_WIDTH = 10; // error: cannot assign a value to static final variable x
            System.out.println(Main.x);
        }
    }

    final이 붙은 상수 이름은 모두 대문자이고 단어는 _로 구분한다.

    2. Methods (메소드)

    메소드 정의

    public class Main {
      modifier returnType methodName([type parameter1[, type parameter2[, ...]]]) {
        // code to be executed
      }
    }

    메소드 이름은 첫 단어의 첫 문자는 소문자, 두번째 단어부터의 첫 문자는 대문자로 한다.

     

    메소드 오버로딩 (Method Overloading)

    다른 파라미터를 사용한다면 같은 이름의 메소드를 여러개 만들 수 있다.

    public class Main {
        static int plusMethodInt(int x, int y) {
            return x + y;
        }
        static double plusMethodDouble(double x, double y) {
            return x + y;
        }
        public static void main(String[] args) {
            int myNum1 = plusMethodInt(8, 5);
            double myNum2 = plusMethodDouble(4.3d, 6.26d);
            System.out.println("int: " + myNum1);
            System.out.println("double: " + myNum2);
        }
    }

    3. 생성자 (Constructors)

    생성자는 객체를 초기화하는 특별한 메소드이다.

    생성자는 클래스의 객체가 생성될 때 호출된다. 

     

    생성자 정의

    생성자는 클래스 이름과 일치해야하며, return type를 가지지 않는다.

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

    클래스의 생성자를 만들지 않으면 Java는 기본적으로 생성자를 하나 만들어준다.

     

    생성자 파라미터

    생성자에 매개변수를 전달할 수 있다.

    public class Main {
        int x;
        int y;
        public Main() {
            this(5);
        }
        public Main(int x) {
            this(x, 4);
        }
        public Main(int x, int y) {
            this.x = x; this.y = y;
        }
        public static void main(String[] args) {
            Main myObj = new Main();
            System.out.println(myObj.x + " " + myObj.y);
        }
    }

     

    attributes, methods, constructors를 위한 access modifier는 public, private, default, protected가 있다.

    • public - 코드는 모든 클래스에서 접근 가능하다.
    • protected - 코드는 같은 패키지 안에서 또는 subclass 에서 접근 가능하다.
    • default - 코드는 같은 패키지 안에서만 접근 가능하다. modifier를 지정하지 않았을 때 사용된다. 
    • private - 코드는 선언된 클래스 내부에서만 접근 가능하다.

    attributes, methods를 위한 non-access modifier는 final, static, abstract, transient, synchronized, volatile이 있다.

    • final - attribute와 method는 오버라이드/변경이 불가능하다. 
    • static - attribute와 method는 객체 대신 클래스에 속한다.
    • abstract - abstract 클래스 안에서만 사용할 수 있고, method에게만 사용할 수 있다. 그 메소드는 body를 가질 수 없다. body는 subclass에 의해 제공된다. 
    • transient - 객체가 serializing 될 때, transient인 attribute와 method는 생략된다.
    • synchronized - 메소드는 한번에 하나의 쓰레드에서만 접근 가능하다.
    • volatile - attribute의 값은 thread 지역에 캐시되지 않고, 항상 메인 메모리에서 읽는다. 

    4. 패키지 (Packages)

    java 패키지는 관련된 클래스를 모아놓은 것이다. 파일들이 들어있는 디렉토리 같은 것이다. 

     

    class 가져오기

    import java.util.Scanner;

    package 가져오기

    import java.util.*;

    유저 정의 패키지

    패키지를 만들기 위해서, 클래스를 패키지 이름 디렉토리의 자식으로 있어야 한다. 

    패키지 이름은 모두 소문자로 이루어진다.

    package mypack;
    class MyPackageClass {
      public static void main(String[] args) {
        System.out.println("This is my package!");
      }
    }

    mypack이라는 디렉토리 안에 MyPackageClass.java파일의 내용이다.

    mypack의 상위 디렉토리로 이동 후, javac 컴파일을 한다.

    javac mypack/MyPackageClass.java

    실행

    java mypack.MyPackageClass

    5. 상속 (Inheritance)

    java에서는 다른 클래스의 속성과 메소드를 상속받는것이 가능하다. 

    subclass (child) - superclass로부터 상속을 받은 클래스

    superclass (parent) - subclass에게 상속을 해준 클래스

    final 클래스는 상속을 해줄 수 없다.

    class SubClass extends SuperClass {
    }

    extends키워드를 사용해 상속받는다. 한 클래스는 하나의 부모 클래스만 상속 가능하다. 다중상속은 interface를 implement한다.

    6. 다형성 (Polymorphism)

    java의 다형성은, subclass가 superclass의 메소드를 재정의하여 다른 작업하는것을 허락하는 것이다.

    class Animal {
        public void animalSound() {
            System.out.println("animal sound");
        }
    }
    class Pig extends Animal {
        public void animalSound() {
            System.out.println("oink");
        }
    }
    class Dog extends Animal {
        public void animalSound() {
            System.out.println("bark bark");
        }
    }
    class Main {
        public static void main(String[] args) {
            Animal animal = new Animal();
            Animal pig = new Pig();
            Animal dog = new Dog();
            animal.animalSound();
            pig.animalSound();
            dog.animalSound();
        }
    }

    7. Inner Class (Nested Class)

    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);
      }
    }

    // 나중에 더 내용 추가 요망

    8. 추상화 (Abstraction)

    abstract class: 객체를 만들 수 없는 제한적인 클래스. 추상적인 메소드와 일반적인 메소드 둘다 가질 수 있다.

    abstract method: abstract 클래스에서만 사용할 수 있고, body를 가지지 않는 메소드.

    abstract class Animal {
        public abstract void animalSound();
        public void sleep() {
            System.out.println("Zzz");
        }
    }
    class Pig extends Animal {
        public void animalSound() {
            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();
        }
    }

    9. 인터페이스 (Interface)

    abstraction을 이루는 또다른 방법으로 Interface가 있다. 

    interface는 완전히 추상화된 클래스로 추상적인 메소드만 가질 수 있다.

    interface는 다른 클래스에게 상속시킬 때, extends 키워드 대신 implements 키워드를 사용한다. 

    interface Animal {
        public void animalSound();
        public void sleep();
    }
    class Pig implements Animal {
        public void animalSound() {
            System.out.println("The pig says: wee wee");
        }
        public void sleep() {
            System.out.println("Zzz");
        }
    }
    class Main {
        public static void main(String[] args) {
            Pig myPig = new Pig(); // Create a Pig object
            myPig.animalSound();
            myPig.sleep();
        }
    }
    • abstract 클래스와 비슷하게, interface는 객체를 만들 수 없다.
    • interface 메소드들은 body를 가질 수 없다.
    • interface를 implement할 때, 모든 메소드들을 재정의 해야한다.
    • interface 메소드들은 기본적으로 abstract이고 public이다.
    • interface 속성들은 기본적으로 public이고 static 이고 final이다.
    • interface는 생성자를 가질 수 없다.

    java는 다수의 상속을 지원하지 않는다. 그러나 다수의 interface를 implement하는것은 지원한다.

    interface FirstInterface {
        public void myMethod(); // interface method
    }
    interface SecondInterface {
        public void myOtherMethod(); // interface method
    }
    class DemoClass implements FirstInterface, SecondInterface {
        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();
        }
    }

    참조: https://www.w3schools.com/java/java_oop.asp

    https://www.oracle.com/java/technologies/javase/codeconventions-namingconventions.html

    -

Designed by Tistory.