TIL 2022-10-07 jquery마지막, 자바 복습(클래스, 정적멤버, 상속 등), 다형성, 추상클래스, 추상메서드

JYR00·2022년 10월 7일
0

TIL

목록 보기
22/60

1. first()

  • first() : 지정한 html 태그 중 첫 번째 태그를 선택
  • 사용법 :
  • 태그.first():
$('#div01 div').first().css({'background-color':'yellow'});
    <div class="container">
      <div id="div01">
        <h3>first() 사용</h3>
        <div class="box">
          <p>div 태그의 자식 태그인 p 태그</p>
          <p>div 태그의 자식 태그인 2번째 p 태그</p>
        </div>
        <div class="box">
          <p>div 태그의 자식 태그인 p 태그</p>
          <p>div 태그의 자식 태그인 2번째 p 태그</p>
        </div>
        <div class="box">
          <p>div 태그의 자식 태그인 p 태그</p>
          <p>div 태그의 자식 태그인 2번째 p 태그</p>
        </div>
      </div>

2. last( )

$('#div02 div').last().css({'background-color':'yellow'});
<div id="div02">
        <h3>last()사용</h3>
        <div class="box">
          <p>div 태그의 자식 태그인 p 태그</p>
          <p>div 태그의 자식 태그인 2번째 p 태그</p>
        </div>
        <div class="box">
          <p>div 태그의 자식 태그인 p 태그</p>
          <p>div 태그의 자식 태그인 2번째 p 태그</p>
        </div>
        <div class="box">
          <p>div 태그의 자식 태그인 p 태그</p>
          <p>div 태그의 자식 태그인 2번째 p 태그</p>
        </div>
      </div>

3. eq( )

$('#div03 p').eq(1) .css({'background-color' : 'yellow'});
 <div id="div03">
        <h3>eq()사용</h3>

        <p>eq() 선택할 p 태그 (0 index)</p>
        <div style="border :1px solid black">
          <p>eq() 선택할 p 태그 (1 index)</p>
        <div style="border : 1px dashed black">
          <p>eq() 선택할 p 태그 (2 index)</p>
        </div>
          <p>eq() 선택할 p 태그 (3 index)</p>
          <p>eq() 선택할 p 태그 (4 index)</p>
        </div>
      </div>

4. filter( )

      <div id="div04">
        <h3>filter() 사용</h3>
        <div >
          <p>filter()로 검색할 p태그 중 하나</p>
          <p class="intro">filter()로 실제로 검색될 p 태그</p>
          <p>중간에 있어도 선택 안 됨</p>
          <p class="intro">선택될 p 태그 2번째 꺼</p>
          <p>이 태그는 선택 안 됨</p>
        </div>
      </div>
  $('#div04 p').filter('.intro').css('background-color', 'yellow');

5. not()

    $('#div05 p') .not('.intro').css('background-color', 'yellow');
<div id="div05">
        <h3>not() 사용</h3>
        <div>
          <p>not()을 사용하여 선택할 첫번째 태그</p>
          <p class="intro">not을 사용하여 제외할 태그</p>
          <p>이것도 선택함</p>
          <p class="intro">not을 사용하여 제외할 태그</p>
          <p>not을 사용하여 선택할 마지막 태그</p>
        </div>
      </div>





객체

  • 프로그램에서 인식할 수 있는 모든 대상
  • 데이터를 저장하고 처리하는 기본 단위

자바스크립트 객체

  • 자바스크립트 안에 미리 객체로 정의해 놓은 것
  • 문서 객체 모델 (DOM): 문서 뿐만 아니라 웹 문서 안에 포함된 이미지,링크,텍스트필드 등 모두 별도의 객체로 관리
  • 브라우저 관련 객체 : 웹 브라우저 정보를 객체로 관리
  • 내장 객체 : 웹 프로그래밍에서 자주 사용하는 요소를 객체로 정의해 놓은 것.


사용자 정의 객체

  • 필요할 때 사용자가 직접 만드는 객체


객체의 인스턴스 만들기

  • new 객체명



배열만들기

  • 초기값 있는 형태로 만드는 것을 권장하는 편.
var numbers = ["one","two","three"];

Array 객체의 메서드는 알아 놓는 걸 추천!!

내장 객체 - Date 객체

  • getFullYear( ) - 연도를 4자리 숫자로
  • getMonth( ) (1-11)
  • getDate( ) (1-31)
  • getDay( ) (0-6)

Date 객체 사용하기

  • 자주 사용된다.
console.log('-----------Date 객체 사용하기---------------');

let now = new Date();

console.log(now);
console.log(now.toLocaleString());
console.log(now.toString());
console.log(now.getFullYear());
console.log(now.getUTCFullYear());

console.log(now.getMonth());
console.log(now.getDate());
console.log(now.getDay());

console.log(`현재 시간 :  ${now.getHours()}`);
console.log(`현재 UTC시간 : ${now.getUTCHours()}`);
console.log(`현재 분 : ${now.getMinutes()}`);
console.log(`현재 초 : ${now.getSeconds()}`);

Math 객체

  • floor( )
  • max( )
  • min( )
  • random( )
  • round( )
  • ceil( )
console.log("\n---------Math 객체 사용하기----------\n");

console.log(`PI : ${Math.PI}`); //3.141592....

let result = 10/3;
console.log(`10 / 3을 그대로 출력 시 ${result}`);  //3.3333..
console.log(`10 / 3 의 소수점 올리기 : ${Math.ceil(result)}`); // 4
console.log(`10/ 3의 소수점 버리기 : ${Math.floor(result)}`); // 3
console.log(`5.5에 대한 반올림 : ${Math.round(5.5)}`); //5부터 반올림된다.
console.log(`5.4에 대한 반올림 : ${Math.round(5.4)}`);
console.log(`매개변수 중 최댓값 선택하기 : ${Math.max(10,20,30,40)}`);
console.log(`매개변수 중 최솟값 선택하기 : ${Math.min(10,20,30,5)}`);





브라우저 관련 객체

  • window( )//
  • document( )//
  • navigator( )
  • history( )//
  • location( )//
  • screen( )

window 객체 프로퍼티

  • localStorage
  • sessionStorage
  • scrollX
  • scrollY

window 객체 메서드

  • alert ( )
  • confirm ( ) // 확인 취소 가능
  • prompt ( )
  • open ( )
  • scroll ( )
  • geolocation( ) -모바일 기기를 이용한 위치 정보

location 객체

현재 문서의 url 주소 정보 담겨있음

  • href : 이 값을 변경하면 해당 주소로 이동 가능
  • reload()

history

  • go( )
  • back( )






문서 객체 모델(DOM)

NODE(노드)

  • DOM트리에서 가지가 갈라져 나간 항목

getElementById( )

요소명.getElementById("id명")

getElementByClassName( )

요소명.getElementByClassName("class명")

querySelector( ), querySelectorAll( )

노드.querySelector(선택자) : 한 개의 값만 반환
노드.querySelectorAll(선택자 혹은 태그 ): 배열 형태로 반환

id는 # class는 .

innerText, innerHTML

innerText : 텍스트 내용 수정
innerHTML : html 태그까지 포함해서 텍스트 내용 지정





DOM의 event객체

  • button : 마우스에서 누른 버튼의 키값을 반환
  • charCode : !!꼭 기억!! keypress 이벤트가 발생할 때 어떤 키를 눌렀는지 유니코드값으로 반환.
  • target :이벤트가 최초로 발생한 대상을 반환. 한 번씩 필요할 때가 있다.



자바스크립트 This

  • 이벤트가 발생한 대상에 접근할 때 사용하는 예약어

css 속성에접근

  • background-color => backgroundColor처럼 카멜 명명법 사용해야..

클래스

  • 객체의 속성(멤버 변수)과 행위(메서드) 선언
  • 객체의 설계도 혹은 틀

객체

  • 클래스의 틀로 찍어낸 실체
  • 인스턴스라고도 부름

생성자

  • 멤버 변수의 초기화 목적으로 실행되는 메소드
  • 객체가 생성되는 순간 자동호출
  • 클래스 이름과 동일한 메서드다. 여러 개 작성 가능
  • 반환타입없다. (return)

기본 생성자

  • 매개변수가 없는 생성자
  • 생성자가 하나도 없을 때는 컴파일러가 기본 생성자 자동으로 생성. 내용비어있음
  • 컴파일러에 의해 기본 생성자가 생성.

this

  • 객체 자신에 대한 레퍼런스
    • 자기 자신을 뜻하는 키워드. this.멤버 형태로 멤버에 접근.
  • 객체 내에서는 this 키워드 생략 가능하다.
  • 쓰는 이유는 매개변수 혹은 지역 변수와 이름이 같은 멤버가 있을 경우, 호출 시 this 사용한다.

this( )

  • 같은 클래스의 다른 생성자 호출
  • 생성자 코드의 제일 처음에 있어야한다.

객체 배열

  • 자바의 객체 배열
    • 객체에 대한 레퍼런스 배열임. -> 사용자가 만든 클래스로 배열 생성시

오버로딩

  • 한 클래스 내에 두 개 이상의 이름이 같은 메소드
  • 매개 변수의 개수,순서,타입이 달라야한다.(이들 중 하나만이라도)

객체소멸 가비지

  • 사용하지 않는 객체 -> 자동으로 삭제해준다.

접근지정자

  • private : 비공개
  • public : 공개

static멤버 (정적멤버)

  • 객체 생성 없이 클래스명으로 접근가능한 멤버.
  • 특징 : 정적 멤버끼리만 사용가능. 객체 멤버는 정적 멤버 접근 가능. 하지만 정적 멤버는 객체 멤버에 접근 불가능.
  • 정적멤버는 데이터 공유한다. 객체멤버는 메모리를 따로 보관한다.
  • 초기화할 때는 static {초기화}

final 키워드

  • 수정 불가능. 사용하는 분야에 따라 달라짐
  • 멤버 변수 : 수정 불가능
  • 멤버 메서드 : 오버라이딩 불가능
  • 멤버 클래스 : 상속 불가능

상속

  • 자식 클래스가 부모 클래스의 멤버를 물려받는 것.
  • 자식이 부모 선택. 필드와 메서드를 상속 받을 수 있다.

  • 부모가 private이면 상속 불가능.
  • 부모가 final이면 수정 불가능.
  • 부모가 다른 패키지에 있을 때 부모가 default일 경우 상속 불가능.

extends

  • 단일 상속을 하기 때문에 한 부모만 가능.

  • 여러 부모 받고 싶으면 interface사용해야

  • 자식 객체 생성하면 부모 객체도 생성된다.

  • 부모 생성자 호출 완료 후 자식 생성자 호출

super(부모 생성자 호출)

  • overloadding 가능.
  • 자식 생성자 무조건 첫줄에 위치

✨ 메서드 재정의!!!(@Override)!!!

  • 부모 클래스의 상속 메서드 수정해 자식 클래스에서 재정의
  • 부모 클래스의 메소드와 동일한 시그니처 가져야.
    => 부모 메서드와 같아야 한다. 내용은 수정 가능.
  • 접근 제한을 더 강하게 오버라이딩 불가능
  • @Override하면 에러날 확률 낮아진다. 쓰는 게 좋다.
  • 메서드 재정의는 부모 메서드 숨기는 효과있다.(부모가 final이면 재정의 불가.)

다형성

  • 같은 타입이지만 실행 결과가 다양한 객체 대입(이용) 가능한 성질

추상클래스

추상

  • 실체들 간에 공통되는 특성을 추출한 것.
    ex) 새, 곤충, 돼지 => 동물(추상)
    삼성,현대,lg => 기업(추상)

추상클래스

  • 실체 클래스들의 공통되는 필드와 메소드를 정의한 클래스
  • 몸통이 없기 때문에 객체 생성 불가능.
  • 자체적으로 생성불가능.
  • 실제 클래스의 공통된 필드와 메소드의 이름 통일할 목적

추상 클래스 선언

상속 통해서 자식 클래스만 생성 가능

public abstract class 클래스{
// 필드
// 생성자
// 메서드
}
  • 추상 클래스에는 메소드 선언부만 작성. (몸통이 없음)

✨다형성

  • 같은 타입이지만 실행 결과가 다양한 객체 대입(이용) 가능한 성질
  • 부모 타입에는 모든 자식 객체가 대입 가능
    - 자식 타입은 부모 타입으로 자동 타입 변환

타이어 규격 정해져 있으면 다양한 회사에서 그 규격에 맞춰 타이어 생산.

자동 타입변환

부모클래스의 변수에 자식 클래스 타입이 자동 타입 변환

타입변환과 객체관리

추상클래스, 추상메서드 예제

animal, dog, cat, animalex

animal

// 추상 클래스 : 추상 메서드를 1개 이상 가지고 있는 클래스를 추상 클래스라 한다. 1개만 있어도 무조건!!
// 추상 클래스는 자체적으로 객체를 생성할 수 없음(변수는 가능) new 사용 불가능.
// 자식 클래스가 추상 클래스를 상속 받았을 경우 반드시 추상 메서드를 오버라이딩해야 함.
// (만약 오버라이딩 하지 않을 경우 자식 클래스도 추상 클래스로 선언해야 함.)
// 추상 클래스는 자식 클래스를 규격화하기 위해 사용함.

public abstract class Animal {
    public String kind;

    public Animal(String kind){
        this.kind = kind;
    }
    public void breathe(){
        System.out.println(this.kind+"가 숨을 쉽니다.");
    }

    public abstract void sound();
}

animalex

public class AnimalEx {
    public static void animalSound(Animal animal){
        animal.sound();
    }
    public static void main(String[] args) {
        Dog dog = new Dog("멍멍이");
        Cat cat = new Cat("냐옹이");

        dog.breathe();
        dog.sound();
        cat.breathe();
        cat.sound();
        System.out.println("===================");

//        Animal animal = new Animal()

//        추상 클래스 타입의 변수를 선언하는 것은 문제가 없음
//        클래스의 형변환

        Animal animal;
//        animal = new Animal(); //본인은 추상 클래스니까 오류남.

        animal = new Dog("멍멍이"); //이건 오류안남
        animal.sound();// .sound(); //멍멍이라고 뜸

        animal = new Cat("고양이");
        animal.sound(); //냐옹

        animalSound(new Dog("멍멍이"));
        animalSound(new Cat("냐냐옹이"));

    }
}

cat

public class Cat extends Animal {
    public Cat(String kind) {
//        this.kind = "포유류";
        super(kind);
    }
    
    @Override
    public void sound(){
        System.out.println("냐옹");
    }
}

dog

public class Dog extends Animal {
    public Dog(String kind){
//        this.kind = "포유류";
        super(kind);
//        this.kind = kind; super생겨서 필요 없어짐.
    }

    @Override
    public void sound() {  //부모꺼를 가져와서(부모꺼는 내용없음) 내용은 본인에게 맞게 수정.
        System.out.println("멍멍");
    }
}

추상 클래스 예제2

phone, phoneex, smartphone

phone

public abstract class Phone {
    public String owner;

    public Phone(String owner){
        this.owner = owner;
    }

    public void turnOn() {
        System.out.println("휴대폰 전원을 켭니다.");
    }

    public void turnOff(){
        System.out.println("휴대폰 전원을 끕니다.");
    }
}

phoneEx

public class PhoneEx {
    public static void main(String[] args){
        SmartPhone smartPhone = new SmartPhone("홍길동");
        smartPhone.turnOn();
        smartPhone.internetSearch();
        smartPhone.turnOff();

        //Phone 클래스는 추상 클래스이므로 new 키워드를 통해 객체 생성할 수 없음
//        Phone phone = new Phone("홍길동") ;

//        Phone phone;
//        phone = new Phone("홍길동"); //추상클래스니까 직접적인 객체 클래스 생성불가능. 자식에게 상속받아 사용해야 한다.
    }
}

smartPhone

public class SmartPhone extends Phone{
    public SmartPhone(String owner){
        super(owner); //
    }

    public void internetSearch(){
        System.out.println("인터넷 검색을 합니다.");
    }


}

다형성 예제1

parents, child, childEx
chap5

public class Parents {
    public void method1(){
        System.out.println("Parent - method1()");
    }

    public void method2(){
        System.out.println("Parent - method2()");
    }
}

child

public class Child extends Parents{
    @Override
    public void method2(){
        System.out.println("Child-method2()");
    }

    public void method3(){
        System.out.println("Child-method3()");
    }
}

childEx

public class ChildEx {
    public static void main(String[] args) {
//        Child child = new Child();
//
//        Parents parents = child;
//        parents.method1();
//        parents.method2();

        Parents parents = new Parents(); //객체 생성
        parents.method1(); //parents.method1()
        parents.method2(); //parents.method2()
        System.out.println("=========");

        Child child = new Child();
        child.method1(); //child에는 method1이 없음. 그니까 부모것인 parents.method1()이 나옴
        child.method2();
        child.method3();

        System.out.println("=========");


        //다형성 : 부모 클래스 타입의 변수에 자식 클래스의 객체를 대입하여 부모 클래스
//        타입의 객체인 것처럼 사용하는 것, 실제 결과물은 자식 클래스 타입의 객체가 가지고 있는 데이터로 출력
        parents = child;  //껍데기는 parents지만 내용물이 child임. 부모님 젊은 시절 옷을 입음.
        parents.method1(); //Parent - method1()
        parents.method2(); // Child-method2()
        //parents.method3(); // 실행 안됨.


//        부모 클래스 타입의 변수에 자식 클래스 타입의 객체를 대입했을 경우 자동 형변환이 발생하여 자식
//        클래스 타입의 객체가 전용을 가지고 있던 멤버를 활용할 수 없음
//        부모 클래스 멤버만 사용할 수 있음.
        
    }
}

다형성 예제2

Tire.class, Car2.class, HankookTire.class, KumhoTire.class, Car2Ex.class, Car3.class

tire

public class Tire {
    public int maxRotation; //최대 회전수
    public int accumulatedRotation; // 누적 회전수
    public String location; // 타이어 위치

    public Tire(String location,int maxRotation){
        this.location = location;
        this.maxRotation = maxRotation;
    }

    public boolean roll(){
        ++accumulatedRotation;

        if(accumulatedRotation < maxRotation){
            System.out.println(location + "Tire 수명 : " + (maxRotation -
                    accumulatedRotation) + "회");
            return true;
        }
        else{
            System.out.println("***" + location +"Tire 펑크 ***");
            return false;
        }
    }
}

car2

public class Car2 {
    Tire frontLeftTire = new Tire("앞왼쪽",6);
    Tire frontRightTire = new Tire("앞오른쪽", 2);
    Tire backLeftTire = new Tire("뒤왼쪽",3);
    Tire backRightTire = new Tire("뒤오른쪽",4);

    int run(){
        System.out.println("[자동차가 달립니다.]");
        if(frontLeftTire.roll() == false){
            stop();
            return 1;
        }
        if(frontRightTire.roll() == false){
            stop();
            return 2;
        }
        if (backLeftTire.roll() == false){
            stop();
            return 3;
        }
        if(backRightTire.roll() == false){
            stop();
            return 4;
        }
        return 0;
    }

    void stop(){
        System.out.println("[자동차가 멈춥니다]");
    }
}

HankookTire

public class HankookTire extends Tire{
    public HankookTire(String location, int maxRotation){
        super(location,maxRotation);
    }

    @Override
    public boolean roll(){
        ++accumulatedRotation;

        if(accumulatedRotation < maxRotation){
            System.out.println(location + "HankookTire 수명 : " + (maxRotation-
                    accumulatedRotation) + "회");
            return true;
        }
        else {
            System.out.println("***" + location + "HankookTire 펑크 ***");
            return false;
        }
    }
}

KumhoTire

public class KumhoTire extends Tire{
    public KumhoTire(String location, int maxRotation){
        super(location,maxRotation);
    }

    @Override
    public boolean roll(){
        ++accumulatedRotation;

        if(accumulatedRotation < maxRotation){
            System.out.println(location + "HankookTire 수명 : " + (maxRotation-
                    accumulatedRotation) + "회");
            return true;
        }
        else {
            System.out.println("***" + location + "HankookTire 펑크 ***");
            return false;
        }
    }
}

car2ex

public class Car2Ex {
    public static void main(String[] args) {
        Car2 car = new Car2();

        for (int i=1; i<=5; i++){
            int problemLocation = car.run();

            switch (problemLocation){
                case 1:
                    System.out.println("앞왼쪽 HankookTire로 교체");
                    car.frontLeftTire = new HankookTire("앞왼쪽",15);
                    break;

                case 2:
                    System.out.println("앞오른쪽 KumhoTire로 교체");
                    car.frontRightTire = new KumhoTire("앞오른쪽",13);
                    break;

                case 3:
                    System.out.println("뒤왼쪽 HankookTire로 교체");
                    car.backLeftTire = new HankookTire("뒤왼쪽",14);
                    break;

                case 4:
                    System.out.println("뒤오른쪽 KumhoTire로 교체");
                    car.backRightTire = new KumhoTire("뒤오른쪽",17);
                    break;
            }
            System.out.println("-------------");
        }
        System.out.println("\n\n");

        Car3 car3 = new Car3();

        for(int i =1; i<=5; i++){
            int problemLocaton = car3.run(); //1부터 시작했고 다른데서 1을 줬기 때문에 1마이너스함.

            if(problemLocaton != 0){
                System.out.println(car3.tires[problemLocaton-1].location + "HankookTire로 교체");
                car3.tires[problemLocaton -1] = new HankookTire((car3.tires[problemLocaton -1].location),15);
            }
            System.out.println("============");
        }
    }
}

car3

public class Car3 {
    Tire[] tires = {
            new Tire("앞왼쪽",6),
            new Tire("앞오른쪽",2),
            new Tire("뒤왼쪽",3),
            new Tire("뒤오른쪽", 4)
    };

    int run(){
        System.out.println("[자동차가 달립니다.]");

        for(int i = 0; i<tires.length; i++){
            if(tires[i].roll() == false){
                stop();
                return (i+1);
            }
        }
        return 0;
    }

    void stop(){
        System.out.println("[자동차가 멈춥니다.]");
    }

}


////////////////////////////////////////////////////////////////////////////////


















0개의 댓글