Dart #4 Classes

Soymilk·2024년 1월 31일
post-thumbnail

#4.0 Your First Dart Class

class를 선언하는 것은 java와 거의 동일하다!

class Player{
  String name = 'jungwoo';

  void sayHello(){
    print("hello $name");     //변수명이 겹치지 않는 이상, this는 사용하지 않는다!
  }
}

#4.1 Constructors

constructor 선언도 java와 똑같다!

class Player{

  String name = 'jungwoo';
  int xp = 2;

  Player(String name, int xp){
    this.name = name;
    this.xp = xp;
  }                                 //1. 기존 방식   

  Player(this.name, this.xp);       //2. Dart에서 가능한 새로운 방식!

}

#4.2 Named Constructor Parameters

function의 named parameter와 동일한 기능을 Constructor에도 사용 가능!

class Player {
  String name = 'jungwoo';
  int xp = 2;

  Player({
    required this.name,
    required this.xp,
  });

  void sayHello() {
    print("hello $name");
  }
}

#4.3 Named Constructors

Dart에서 생성자를 만드는 새로운 방법!

class Player {
  String name = 'jungwoo';
  int xp = 2;

  Player({required this.name, required this.xp,});

	Player(String name, int xp){
	
		this.name= name;
		this.xp = xp;
	
	}

	Player(void){
		this.Player("jungwoo",100);	
	}
	

  Player.newObjectWithFixedXP({required String name}) //parameter는 positional이나 named 상관없다
      : this.name = name,
        this.xp = 100;

}

#4.4 Recap

#4.5 Cascade Notation

void main() {
  var JW = Player(name: "jungwoo", xp: 100);
  JW.name = 'NotJungwoo';
  JW.xp = 200;

  var JW = Player(name: "jungwoo", xp: 100)
    ..name = 'dkl'
    ..xp = 290
		..sayHello();    //colon은 마지막에만 넣기!
}

일일이 JW객체에 매 번 접근해서 수정하는 대신, .. <= 요거를 이용해서 바로 수정할 수 있다.

또한 cascade notation을 이용하면 순차적으로 function도 같이 수행이 된다!

#4.6 Enums

c언어의 Enum과 거의 동일함!

enum Level { one, two, three } //enum 생성하기!

class Player {
  String name = 'jungwoo';
  int xp = 2;
  Level level = Level.one;     //클래스 변수에 접근하듯 값을 가져옴

  Player({
    required this.name,
    required this.xp,
    required this.level
  });

  Player.newObjectWithFixedXP({
    required String name,
    required Level level,
  })  : this.name = name,
        this.xp = 100,
        this.level = level;  

}

#4.7 Abstract Classes

java의 추상클래스와 거의 완전 동일함.

abstract class AClass{
	abstract void printhello();
}

class BClass extends AClass{
	void printhello(){
		print("hello");
	}
}

추가 요소로 Mixin이 있다고 하는데 4.9에서 배워보자

#4.8 Inheritance

이것 역시 java와 동일함!

부모클래스의 생성자는 super 키워드를 통해서 호출함. 이것도 java와 동일.

#4.9 Mixins

java에서의 인터페이스라고 생각하면 편함.

(간단히) 생성자가 없는 클래스다!!

인터페이스와 조금 다른 점은,

‘구현’의 의미 보다는 ‘함수와 변수 가져오기’의 의미로 사용됨.

예제:

mixin class Strong {. // mixin 클래스명  // mixin class 클래스명 
  final int power = 999;
	
	void printhello(){
		print("hello");
	}

}

class Player with Strong, Powerful, Tall { 
	printhello();
... }

질문: 여기에서 mixin 클래스 선언문에 mixin을 달아주지 않으면 오류가 뜨던데,
강의에서는 오류가 뜨지 않았음!

0개의 댓글