냥코딩쟝
Published 2023. 2. 19. 18:38
Day16-객체,메서드 -java spring notes-
package days16;

public class Car {
   
   // 필드
   String name;
   String gearType; // 수정, 자동
   int door;
   
   // 클래스 필드
   static  Member member;
   
   // [참조타입의 필드는 new 생성되었는지 꼭 확인]
   // 엔진 필드
   // 필드를 priavte 접근지정자로 설정하는 이유 ? 
   // getter, setter
   private Engine engine = null;  // has-a 관계

   public Engine getEngine() {
      return engine;
   }

   public void setEngine(Engine engine) {
      // 장착할 수 있는 유효한 엔진 체크 한 후 장착..
      this.engine = engine;
   }
   
   
   // Car 클래스랑 Engine 클래스 랑  일체형(결합력)이 높은 코딩. -> 좋은 코딩이 아니다.  왜?   ( 시험 )
   // Engine engine = new Engine();     
   

   // 3:05 수업 시작
   // 생성자
   Car(){
      
   }
   
   public Car(Engine engin) {
      this.engine = engin;
   }

   // 메서드
   void speedUp( int fuel ) {
      // engine 객체가 생성 ( 확인 ) 
      this.engine.moreFuel(fuel);  // NullPointerException 에러 발생.
   }
   
   void speedDown( int fuel ) {
      this.engine.lessFuel(fuel);
   }
   
   void stop() {
      this.engine.stop();
   }

} // class


public class Engine {
   
   // 필드
   int speed;
   
   // 생성자
   
   // 메서드
   void moreFuel(int fuel) {
      this.speed += fuel * 0.05;
   }
   
   void  lessFuel(int fuel) {
      this.speed -= fuel * 0.05;
   }
   
   void stop() {
      this.speed = 0;
   }

public class Ex01 {

   public static void main(String[] args) {
      // 9:40  제출~
      // 10:03 수업 시작~~ 
      String n = "keNik";   
      String m= "kKnie";   
      
      // 1)  대문자로 변환   KENIK               KKNIE
      // 2) 정렬                  EIKKN               EIKKN
      // 3) 두 문자열이 같냐 ? 
      
      // System.out.println(  n.toUpperCase() );
      
      // 1) n, m  모두 대문자로 변환..
      //   'a' -32    ->   'A'
      /*
      for (int i = 0; i < n.length() ; i++) {
         char one =  n.charAt(i);
         if( 'a' <= one  && one <= 'z' ) {
             System.out.println(   (char)(one - 32)  );
         }else {
            System.out.println( one );
         }
      }
      */

   } // main

} // class

 

 

public class Ex02 {

   public static void main(String[] args) {
      // [this 설명]
      // [생성자 this 설명]  왜?  생성자 필드 초기화~/  또 다른 생성자를 this() this(age) 호출합니까? 
      // [리턴값 this 설명]   11:10 수업 시작~
      
      Person p1 = null;
      p1 = new Person("홍길동", 20); // 객체 생성될 때 디폴트 생성자 호출됨.
      //p1.name = "홍길동";  // NullPointerException
      //p1.age = 20;
      
      //p1 = new Person(20); // 객체 생성될 때 디폴트 생성자 호출됨.
      
      p1.dispPerson();
      
      // 객체 복사
      //Person p2 = p1.plusAge(5);    //  this==p1==0x1 주소
      //p2.dispPerson();
      
      p1.plusAge(5).dispPerson();

      
      Person p5 = new Person();
      p5.plusAge(4);
   } // main

} // class

class Person{
   // 필드
   String name;
   int age;
   // 생성자 X
   public Person() {
      this.name = "익명";
      this.age = 0;
      System.out.println("1");
   }
   public Person(String name, int age) { 
      // 필드 초기화.
      this(age);  // 모든 코딩의 제일 위에 선언(코딩)한다.
      this.name = name;
      //this.age = age;
      System.out.println("3");
   }
   
   public Person(int age) {
      this();  // 디폴트생성자
      this.age = age;
      System.out.println("2");
   }
   // 메서드 X
   // p1.dispPerson()
   // this == p1== 0x1
   // this.필드
   public void dispPerson() {
      System.out.printf("name=%s, age=%d\n", this.name, age);
   }
   
   // [참조형 리턴타입]
   // p1.plusAge(5);   this== p1 
   // p5.plusAge(4);  this== p5
   public Person plusAge( int n ) {
      // p1 == this == 0x1
      this.age += n;
      return this;  // 참조형 리턴타입              this 리턴
   }
}
public static void main(String[] args) {  // 프로그램 시작~ 
      
      // Save 클래스  클래스 변수  rate 메모리에 로딩되어져 있다.
      // [클래스 변수를 사용하는 방법 ?   클래스명.클래스변수 ]
      
      // 아버지한테 자동차를 물려받았어요. + 20 X 면허증 X
      // The field Save.rate [ is not visible ]
      //        System.out.println( Save.rate  );
      
      System.out.println( Save.getRate() );
      Save.setRate(0.08);
      System.out.println( Save.getRate() );
      
      // 멤버 사용하는 방법. ?      객체명.필드명 ,   객체명.메서드명()
      
      
      /*
       * 1. static 키워드 설명
       * 2. 저축관련 Save 클래스 선언
       *     필드 :  private 예금주, 예금액, 이자율
       *     getter/setter 선언
       *     생성자 : 2
       *     메서드 : 예금정보 출력메서드 
       * 3. Ex06.java 
       * */
      
      // 문제점: 기업은행 /보통예금
      //             이자율:005
    
      Save [] ps = {
             new Save("김예지", 10000, 0.05),
             new Save("이혜진", 4000, 0.05),
             new Save("박민종", 16000, 0.05),
             new Save("이태규", 65000, 0.05),
               new Save("탁인혁", 1000, 0.05)
      } ;
      
      // Save.setRate( 0.01 );
      // 객체
      ps[1].setRate(0.09);
      
      for (int i = 0; i < ps.length; i++) {
         ps[i].dispSave();
      }
   
      // [정적메서드 == static 메서드]
      // 프로그램이 시작되면 클래스가 로딩되면서 static 메서드도 자동으로 메모리(Method Area)에 로딩된다.
      // public static double getRate(){}
      // public static void setRate(){}
      // 질문 ) 어떤 경우에 "static 메서드"로 선언합니까? 
      //            1) private static double rate ;  처럼 private 로 선언된 클래스 변수를 사용하기 위해서...
      //            2) 인스턴스를 사용하지 않아도 호출(사용) 가능한 메서드 이기 때문에
       //                자주 사용되는 메서드는 static 메서드로 선언한다. 
      
      // 수학과 관련된 메서드를 구현한 클래스 : Math클래스 
      // 모든 메서드가 static 메서드 이기 때문에 객체를 생성할 필요없이
      // 클래스명으로 바로 사용가능하다. 
      //                                 클래스명.static메서드()
      System.out.println(  Math.random()  );
      System.out.println(  Math.PI  );
      System.out.println(  Math.abs( -100 ) );
      System.out.println(  Math.max(3, 5)  );
      System.out.println(  Math.min(3, 5)  );
      System.out.println( Math.pow(2,  3) );

   } // main

} // class
public class Ex04 {

   public static void main(String[] args) {
      // 12:10 수업 시작~~
      /*
       *  1. 변수
       *     1) 지역변수
       *     2) 인스턴스 변수
       *     3) 클래스(static) 변수
       *     
       *  2. 메서드 
       *     1) 인스턴스 메서드
       *     2) 클래스(static) 메서드   
       *     
       *  3. 클래스를 설계할 때,   필드 중에 모든 인스턴스가 공유해야할 필드가 있다면      static 변수 로 선언한다.   
       *      클래스 변수는  인스턴스를 생성하지 않아도 클래스명.static변수 로 사용할 수 있다. 
       *      클래스 메서드는 인스턴스 변수를 사용할 수 없다. 
       *      메서드 내에서 인스턴스 변수를 사용하지 않는다면, static 을 붙이는 것을 고려한다. 
       *      
       * */
      
      // 클래스명.static필드
      // System.out.print();
      
      // 클래스명.static메서드
      // Math.random();

      // System.out.println(  Ex04.sum( 1,2 )   );
       System.out.println(  sum( 1,2 )   );
      
      //  sum() 같은 클래스 안에 있는 main() 메서드에서 호출하기 때문에  클래스명 생략
      
      //Ex04 obj = new Ex04();
      //obj.sum(1, 3);
      
   } // main
   
   public static  int sum( int a, int b) {
      return a+b;
   }

} // class
public class Ex05 {

   public static void main(String[] args) {
      /*
       * [ final 키워드 ]  ( 시험 ) final 키워드에 대해서 설명하세요~
       * 1. 변수 앞에         선언할 때   -   상수
       *     지역변수
       *     매개변수
       *      
       *     인스턴스 변수
       *     클래스 변수
       *      
       * 2. 메서드 앞에    선언할 때 
       * 3. 클래스 앞에     선언할 때 
       * */
      
      // System.out.println( Sample.PI );
      
      Sample s = new Sample(100);
      s.plus(100);
      System.out.println( s.m );  // 110

   }

}

class Sample{
   // 인스턴스 변수
   // double pi = 3.141592;
   // final double PI = 3.141592;  // 상수
   
   // 클래스 변수
   // static final double PI = 3.141592;  // 상수
   // public final static  double PI = 3.141592;  // 상수
   
    final int MAX_VALUE ;  // 명시적 초기화
   // 생성자
   public Sample(  int maxValue ) {
      this.MAX_VALUE = maxValue;
   }
   
   void disp() {
      // 지역변수
      final int COUNT = 10;  // 상수
   }
   
   int m = 10;
   void plus( final int n ) {  // 여기서 final 의미 ?  지역변수 앞에 final
      // n = 30;
      m += n;
   }
}
public class Ex05_02 {

   public static void main(String[] args) {
      

   }

}

//subclass(자식클래스)를 가질 수 없는 마지막(최종) 클래스
final class P{
   
   // final 메서드 앞에 붙이면 자식 클래스에서 
   // 오버라이딩(재정의)을 할 수 없다.
   final void draw() {
      System.out.println("P.draw() 호출됨.");
   }
   
}

// The type C cannot subclass the final class P
// 
//class C extends P{
    
   // Cannot override the final method from P
   /*
   @Override
   void draw() {
      System.out.println("C.draw() 오버라이딩(재정의) 호출됨.");
   }
   */
   
//}

public class Ex06 {

   public static void main(String[] args) {
      // 왜 ? 질문
      // A obj =  new A();
      // B obj =  new B();
      // C obj =  new C();
      // 답 : 다형성..
      
      /*
      A obj = new A();
      obj.disp();
      */
      
      /* (질문)
      Regular 객체를 생성해서 basePay는 출력이 되지만 
      Employee 클래스에는 basePay라는 변수가 없는데
      basePay라는 값은 어디에 저장이 되는건가요 ?
      
      실제 객체( Regular)의 dispEmpInfo() 메서드가 호출이 되어져서 그렇습니다. 
      
      */
      
      // 클래스 간의 형변환 (A,B)
      // 1. 조건 :  상속 관계
      // 2. 업캐스팅 =  자동으로 형변환이 된다.
      
      // A - B - C 상속 계층구조
      A  obj =  new C();  // 업캐스팅
      
      // 다운캐스팅 - 자동되지 않아요.  강제형변환 - cast 연산자
      C  c1 = (C) obj;
      obj.disp();

   }  // main

} //  class

abstract class A{
   abstract void disp() ;
   //{
   // System.out.println("A");
   //}
}

class B extends A{
   // 부모의 추상 메서드를 오버라이딩(재정의)해서 추상메서드를 구현하면 객체는 생성할 수 있다.
   @Override
   void disp() {
      System.out.println("B - 재정의");
   }
}

class C extends B{
   @Override
   void disp() {
      System.out.println("C - 재정의");
   }
}
public class Ex07 {

   public static void main(String[] args) {
      // ArrayList 클래스
      // ArrayList   list = new ArrayList();
      
      // 업캐스팅, 다형성
       // List  list = new ArrayList();
      
      test( new ArrayList() );

   } // main
   
   //                               매개변수 다형성
   public static void test( List list)   {
      
   }
   

} // class

public class Ex08 {

   public static void main(String[] args) {

      /*
      Sington s = new Sington();    
      System.out.println(  s );  // 생성된 객체의 정보 :   days17.Sington@5aaa6d82      
        // s = new Sington();
      Sington s2 = s;
      System.out.println(  s2 );  // 생성된 객체의 정보 :   days17.Sington@73a28541
       */

      // 어디에서도 객체를 생성할 수 없다..
      // The constructor Singleton()  [is not visible]
      // Singleton s = new Singleton();
      Singleton s =  Singleton.getInstance();
      System.out.println( s );
      s =  Singleton.getInstance();
      System.out.println( s );
      s =  Singleton.getInstance();
      System.out.println( s );
      s =  Singleton.getInstance();
      System.out.println( s );
   } // main

} // class

// 싱글톤 
class Singleton{

   // public                패키지 내/외 어디서든 객체생성할 수 있다.
   // default            패키지 내에서만 객체를 생성하세요.. ( 제한 )
   // protected                             "                                                     + 상속
   private Singleton() { }

   private static Singleton singleton = null ;  // 필드 선언

   public static Singleton getInstance() {
      // static 메서드 안에서 지역변수       사용가능 ? O
      // static 메서드 안에서 인스턴스변수 사용가능 ? X
      // Cannot make a static reference to the non-static field singleton
      if( singleton == null ) {
         singleton = new Singleton();
      }     
      return singleton;

   }

}
public class Ex08 {

   public static void main(String[] args) {

      /*
      Sington s = new Sington();    
      System.out.println(  s );  // 생성된 객체의 정보 :   days17.Sington@5aaa6d82      
        // s = new Sington();
      Sington s2 = s;
      System.out.println(  s2 );  // 생성된 객체의 정보 :   days17.Sington@73a28541
       */

      // 어디에서도 객체를 생성할 수 없다..
      // The constructor Singleton()  [is not visible]
      // Singleton s = new Singleton();
      Singleton s =  Singleton.getInstance();
      System.out.println( s );
      s =  Singleton.getInstance();
      System.out.println( s );
      s =  Singleton.getInstance();
      System.out.println( s );
      s =  Singleton.getInstance();
      System.out.println( s );
   } // main

} // class

// 싱글톤 
class Singleton{

   // public                패키지 내/외 어디서든 객체생성할 수 있다.
   // default            패키지 내에서만 객체를 생성하세요.. ( 제한 )
   // protected                             "                                                     + 상속
   private Singleton() { }

   private static Singleton singleton = null ;  // 필드 선언

   public static Singleton getInstance() {
      // static 메서드 안에서 지역변수       사용가능 ? O
      // static 메서드 안에서 인스턴스변수 사용가능 ? X
      // Cannot make a static reference to the non-static field singleton
      if( singleton == null ) {
         singleton = new Singleton();
      }     
      return singleton;

   }

}
 
public class Ex09 extends Object{

   public static void main(String[] args) {
      
      // Shape s = new Shape();
      // s.           9개의 메서드 보이더라.        왜? 나의 메서드
      // 사실 :  모든 클래스의 최상위 수퍼클래스는  java.lang.Object 클래스이다.
      // Object 가 가지고 있는 메서드들 공부 먼저 해야 겟네요.. 
      
      Point center = new Point(50, 50);
      int radius = 10;
      Circle c = new Circle( center, radius ) ;
      
      c.color = "red";
      // Shape 부모클래스로 부터 상속받은 draw() 메서드는 color 색만 출력(그리고 있다).
      // Shape 부모클래스로 부터 상속받은 draw() 메서드를 수정해서 사용하고 싶다. 
      //                                                                                  재정의
      // 원의 원점 출력 + 색깔 출력
      // 오버라이딩( override ) == 재정의함수
      // 오버로딩( overload )     == 중복함수
      c.draw();  
      // [color=red] 
      // [color=red, center=(50, 50)]
      
      System.out.println( "-".repeat(30) );  // ------------------------------
      
      Point [] p = {
            new Point(1,1),
            new Point(20,40),
            new Point(10,5)
      };
      Triangle t = new Triangle(p);
      t.draw();

   } // main

} // class

// 도형 클래스 
// 자바는 컴파일러가 자동으로 Object 상속받도록 처리..
//class Shape extends Object{
class Shape{
   // 필드
   String color = "black"; // 명시적 초기화
   // 생성자
   // 메서드
   void draw() {
      System.out.printf("[color=%s]\n", color);
   }
}

class Point{
   // 필드
   int x;
   int y;
   // 생성자
   Point(int x, int y){
      this.x = x;
      this.y = y;
   }
   Point(){
      this(0,0);  // 또 다른 생성자를 호출하는 this
   }
   // 메서드
   String getXY() {
      return String.format("(%d, %d)", this.x, this.y);
   }
   
}

// 도형 : 원, 삼각형, 사각형, 마름모 등등 
/*
class Circle{
   // 필드  
   int x;// 원점
   int y; 
   int r;   // radius// 반지름
   
   // 생성자
   Circle(){
      this(0,0,0);
   }
   Circle(int x, int y, int r){
      this.x = x;
      this.y = y;
      this.r = r;
   }
}
*/
class Circle extends Shape{   // is-a 관계
   // 필드  
   Point center ; // 원점             // has-a 관계
   int r;   // radius// 반지름
   
   // 생성자
   Circle(){
      this(  new Point(0, 0)  ,0);
   }
   
   // 원점을 생성자를 통해서 의존성 주입( DI )
   Circle( Point center , int r){
      this.center = center;
      this.r = r;
   }

   // @Override  재정의함수             Annotation ( 애노테이션 )
   @Override
   void draw() {
      System.out.printf("[color=%s, center=(%d, %d)]\n", color, this.center.x, this.center.y);
   }
   
}

// 삼각형 클래스 
// 한 평면상에 있고 일직선상에는 없는 3개의 점 A, B, C를 2개씩 쌍으로 하여 선분을 연결하여 이루어지는 도형.
class Triangle extends Shape{
   // 필드
   // 꼭짓점 3개
   Point [] p = new Point[3]; // 배열
   
   Triangle(  Point [] p  ) {
      this.p = p;
   }

   // 삼각형을 그려주는 함수를 부모로 부터 물려받아서 재정의 함수. == 오버라이딩( override )
   @Override
   void draw() {
      System.out.printf("[p1=%s, p2=%s, p3=%s]\n"
            ,  p[0].getXY(),  p[1].getXY(),  p[2].getXY());
   }
   
}

// 상속관계 (   is-a 관계 )
// 삼각형은 도형이다.
// 원은 도형이다.
 
 
public class Point2D {   
   // 필드
   public int x;
   public int y; 
   
   // 생성자 상속되지 않는다. 
   public Point2D() {
      System.out.println("> Point2D 디폴트 생성자 호출됨...");
   }
   public Point2D(int a) { 
      this.x = a;
      this.y = a;
      System.out.println("> Point2D 1 생성자 호출됨...");
   }  
   public Point2D(int x, int b) {
      this(); 
      this.x = x;
      y = b;
      System.out.println("> Point2D 2 생성자 호출됨...");
   }
   // 메서드
   public void dispPoint2D() {
      System.out.printf("x=%d, y=%d\n", this.x, this.y);
   }
 
   public Point2D offsetPoint(int i) {
      x += i;
      y += i;
      return this;
   }
    
   public void offsetPoint( Point2D p ) {   // MyPoint p = p1  객체 복사
      x += p.x;  //  p2.x  = p2.x +  p1.x
      y += p.y;  // p1.y
   }

   public int getX() {
      return x;   
   }
 
   public Point2D plus(Point2D p) {
      int xValue =  x + p.x;
      int yValue =  y + p.y;
      
      Point2D newp = new Point2D();
      newp.x = xValue;
      newp.y = yValue;
      
      return newp;
   }
   
   public Point2D test(Point2D p) {
      System.out.println("test() 호출됨.");
      return p;
   }

}
public class Point3D extends Point2D{
   // 필드
   // x, y
   public int z;
   
   // 생성자
   // 메서드
   
}

'-java spring notes-' 카테고리의 다른 글

객체 복습-day15~day18(자바의정석 기초 객체2+참고소스 복습)  (0) 2023.02.22
day17-추상클래스, 메서드  (0) 2023.02.19
day15-객체  (1) 2023.02.18
day12-배열  (0) 2023.02.18
Day14  (0) 2023.02.16
profile

냥코딩쟝

@yejang

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!