카테고리 없음

본 캠프 9일 차_Flutter이론 학습 1-16 및 네티워킹

개발일지27 2025. 3. 13. 20:57

Class : 객체와 구조를 정의하는 툴

객체: Class에서 정의한 구조를 기반으로 생성된 실제 데이터

 

클래스 -속성과 메서드가 있다

속성-클래스 안에서 작업을 수행할 때 사용하는 데이터-인스턴스 변수/정적변수/지역 변수

메서드-객체의 동작을 정의하는 함수-인스턴스 메서드/정적 메서드

 

인스턴스 변수 - 객체에 속해있는 변수

 

class Person {
  String name = '강미래';   
int age = 25;             //name, age가 인스턴스 변수

 


}

 

  • this를 통해 접근 가능(class내에서 객체를 가르킬 때 사용
  • 클래스에서 클래스 안의 속성이나 메서드를 사용할 때
  • 클래스에서 인스턴스 변수와 메서드에 속한  변수를 구분할 때

#특징

클래스의 모든 곳에 접근 가능

객체가 존재하는 동안 계속 메모리 상에 존재 가능

동일한 클래스로 생성한 객체들이어도 각 객체들은 값을 공유하지 않고, 개별적인 값을 가진다

 

 

지역 변수- 특정 코드 블록 안에 선언된 변수

  • 변수가 선언된 코드 블록 안에서만 사용할 수 있다
  • 변수가 선언된 코드 블록의 실행이 끝나면 메모리 상에 사라진다.

class Person {
String name = '강미래';

void sayName() {
String nameSentence = '내 이름은 $name !';            //nameSentence는 sayName()안에 선언된 지역 변수
print(nameSentence);
}

void sayNameAgain() {
print(nameSentence); // 오류 발생
}
}

 

 

 

정적 변수 (클래스 변수)- 객체에 종속되지 않고, 클래스 자체에 속하는 변수

  • 클레스 이름을 통해 접근 가능
  • 객체를 통헤 접근 불가
  • this를 통해 접근 가능
  • 객체마다 개별적인 값을 갖지 않고, 모든 객체가 서로 값을 공유

#헷갈렸던 부분-해결

 

class Circle {
  static double pi = 3.14159;           //static: 정적변수 선언
  double radius = 0;
}

void main() {
print(Circle.pi); // 3.14159                //클래스에 속해있는 변수이기 때문에 바로 사용 가능
print(Circle.radius); // Error: Member not found: 'radius'.
}

===========================vs===================================

class Circle {
  static double pi = 3.14159;
  double radius = 0;                           //radius의 경우 인스턴스 변수
}

void main() {
Circle circle = Circle();                         //radius를 사용하기 위해서는 가져와야 된다
print(circle.radius); // 0
print(circle.pi); // 오류 발생
}

 

 

 

###과제

import 'dart:io';

class Product {
String name;
int price;

Product(this.name, this.price);
}

class ShoppingMall {
List<Product> products = [
Product("셔츠", 45000),
Product("원피스", 30000),
Product("반팔티", 35000),
Product("반바지", 38000),
Product("양말", 5000)
];

Map<String, int> cart = {};
int totalPrice = 0;

void showProductList() {
print("\n상품 목록:");
for (var product in products) {
print("${product.name} / ${product.price}원");
}
}

void addToCart() {
print("\n상품 이름을 입력해 주세요 !");
String? productName = stdin.readLineSync();

if (productName == null || productName.isEmpty) {
print("입력값이 올바르지 않아요 !");
return;
}

var product = products.firstWhere(
(p) => p.name == productName,
orElse: () => Product("", 0));

if (product.name == "") {
print("존재하지 않는 상품입니다 !");
return;
}

print("상품 개수를 입력해 주세요 !");
String? countInput = stdin.readLineSync();

try {
int count = int.parse(countInput!);
if (count <= 0) {
print("0개보다 많은 개수의 상품만 담을 수 있어요 !");
return;
}

cart[product.name] = (cart[product.name] ?? 0) + count;
totalPrice += product.price * count;
print("장바구니에 상품이 담겼어요 !");
} catch (e) {
print("올바른 숫자를 입력해 주세요 !");
}
}

void showTotalPrice() {
print("\n장바구니에 ${totalPrice}원 어치를 담으셨네요 !");
}
}

void main() {
ShoppingMall shop = ShoppingMall();
bool isRunning = true;

while (isRunning) {
print("\n------------------------------------------------");
print("[1] 상품 목록 보기 / [2] 장바구니에 담기 / [3] 장바구니에 담긴 상품의 총 가격 보기 / [4] 프로그램 종료");
print("------------------------------------------------");

print("원하는 기능의 번호를 입력하세요: ");
String? input = stdin.readLineSync();

switch (input) {
case "1":
print("\n[1] 상품 목록 보기");
shop.showProductList();
break;
case "2":
print("\n[2] 장바구니에 담기");
shop.addToCart();
break;
case "3":
print("\n[3] 장바구니에 담긴 상품의 총 가격 보기");
shop.showTotalPrice();
break;
case "4":
print("\n이용해 주셔서 감사합니다~ 안녕히 가세요 !");
isRunning = false;
break;
default:
print("\n지원하지 않는 기능입니다 ! 다시 시도해 주세요 ..");
}
}
}