본문 바로가기

MOBILE/Android

안드로이드 세뇌교실 2

 

 

겜팔이

겜팔이의 심심함 해소용

www.youtube.com

 

2-A Java 클래스

- 우리는 객체를 지향한다 : OOP (Object-Oriented Programming) / Java, C++, C#, Object-C 등

- 제일 중요한 건 객체(Object)

- 객체 : 정보(변수) + 행동(메소드) / 내가 작성한 class에 숨을 불어넣어 만든다.

- 클래스 안에 클래스를 넣을 수도 있다. 

 

2-B Java 클래스 (실습)

- 게임 만들기 실습 (알차다!)

public class HelloWorld{


    static class Player {
        String name;
        int hp;
        int atk;
        
        public Player(String name, int hp, int atk) {
            this.name = name;
            this.hp = hp;
            this.atk = atk;
        }
        
        public void attack(Enemy enemy) {
            System.out.println("Player Attack!");
            enemy.hp -= this.atk;
            System.out.println("Enemy hp : " + enemy.hp);
        }
        
        public boolean isLive() {
            if (hp <= 0) {
                return false;
            }
            else {
                return true;
            }
        }
    }
    
    static class Enemy {
        String name;
        int hp;
        int atk;
        
        public Enemy(String name, int hp, int atk) {
            this.name = name;
            this.hp = hp;
            this.atk = atk;
        }
        
        public void attack(Player player) {
            System.out.println("Enemy Attack!");
            player.hp -= this.atk;
            System.out.println("Player hp : " + player.hp);
        }
        
        public boolean isLive() {
            if (hp <= 0) {
                return false;
            }
            else {a
                return true;
            }
        }
    }
    
     public static void main(String []args){
        Player player = new Player("gamepari", 100, 12);
        Enemy enemy = new Enemy("Orc", 80, 5);
        
        while(player.isLive() && enemy.isLive()) {
            player.attack(enemy);
            if(!enemy.isLive()) break;
            enemy.attack(player);
        }
        
        if (player.isLive()) {
            System.out.println("player win");
        }
        else {
            System.out.println("enemy win");
        }
     }
}

 

2-C Java 상속

- 부모와 자식 : 모든 클래스는 Object라는 클래스를 상속받는다.

- class Monster extends Unit { ~~ } <- 객체를 계승하는 것. 하나만 상속 받을 수 있음.

 

2-D Java 상속 (실습)

- 게임 만들기 실습 (좀 복잡.,)

public class HelloWorld{  
	 public static void main(String []args){
	    PlayerCharactor player = new PlayerCharactor("gamepari", 70, 12);
	    EnemyCharactor enemy = new EnemyCharactor("Orc", 80, 5);
	    
	    while(player.isLive() && enemy.isLive()) {
	        player.attack(enemy);
	        if(!enemy.isLive()) break;
	        enemy.attack(player);
	        System.out.println("-----------------------------------");
	    }
	    
	    if (player.isLive()) {
	        System.out.println("player win");
	    }
	    else {
	        System.out.println("enemy win");
	    }
	 }
}
public class Charactor {
	String name;
	int hp;
	int atk;
	
	public Charactor(String name, int hp, int atk) {
		this.name = name;
        this.hp = hp;
        this.atk = atk;
	}
	public void attack(Charactor enemy) {
		System.out.println(this.name + " Attack!");
		enemy.hp -= this.atk;
		System.out.println(enemy.name + " HP : " + enemy.hp);
	}
	
	public boolean isLive() {
		if (hp <= 0) {
            return false;
        }
        else {
            return true;
        }
	}
}
public class PlayerCharactor extends Charactor {
	public PlayerCharactor(String name, int hp, int atk) {
		super(name,hp,atk);
	}
	
	public void heal() {
		hp += 20;
		System.out.println(name +" HEAL!!!");
		System.out.println(name +" HP : " + hp);
	}
}
public class EnemyCharactor extends Charactor{
	public EnemyCharactor(String name, int hp, int atk) {
		super(name,hp,atk);
	}
	
	@Override
	public void attack(Charactor enemy) {
		
		if(hp <= 20) {
			System.out.println("Orc is ANGRY....!!!!!");
			this.atk += 15;
		}
		
		super.attack(enemy);
		
		PlayerCharactor player = (PlayerCharactor)enemy;
		
		if (player.hp <= 30) {
			player.heal();
		}
	}
}

 

2-E Java 예외처리

- 예외는 있는 법 : 특정 메소드는 실패할 경우가 있다. 실패 했을 때 자연스럽게 대처하는 코드 작성.

- try, catch, (finally)

 

2-F Java 예외처리 (실습)

- 로그인 과정 실습

public class HelloWorld{
    public static void main(String []args) {
        try{
            boolean isSucess = login("g82", "1111112");
            if (isSucess) System.out.println("Login success");
            else System.out.println("Login Failed");
        }
        catch (Exception e) {
            System.out.println(e.getMessage());
        }
        finally {
            System.out.println("Copyright g82 2020");
        }
    }

    static boolean login(String id, String pw) throws Exception {
        
        // Android -> "g82", "1111112" -> Server
        
        boolean isNetworkFailed = true;
        boolean isNoId = false;
        boolean isPasswordWrong = false;
        boolean isPWExpired = true;
        
        if (isNetworkFailed) throw new Exception("Network Failed");
        else if (isNoId) throw new Exception("user ID no exist");
        else if (isPasswordWrong) throw new Exception("Password Wrong");
        else if (isPWExpired) throw new Exception("Need change password.");
        
        return true;
    }
}

 

2-G Java interface 파트1

- 인터페이스의 쓰임새 : UI 아님! 다중 상속(파트1). 콜백 메소드(파트2).

- 다중 상속 : 자바에서는 2개 이상의 상속이 불가능하다. '상속'(extends)대신 '구현'(implements)하자. 인터페이스로!

- 상속 : extends. 아이덴티티(identity) 보유. ex) 개는 동물이다. / 사람은 포유류다.

- 구현 : implements. 역할(role)을 부여. ex) 개는 애완동물이다. / 사람은 프로그래머다. << 변수 상속 x >>

 

2-H Java interface 파트1 (실습)

- 동물 농장 

public class HelloWorld {
	public static void main(String []args) {
		Animal dog = new Dog("baduk");
		Animal cat = new Cat("nyaong");
		Animal wolf = new Wolf("waoooo");
		
		Pet pet1 = new Cat("nyaong");
		Pet pet2 = new Dog("baduck");
		
		
		dog.cry();
		cat.cry();
		wolf.cry();
		
		pet1.FoodCall();
		pet2.FoodCall();
		
		((Cat)pet1).cry();
	}
}
public abstract class Animal {
	public String name;
	public Animal(String name) {this.name = name;}
	public abstract void cry();
} 

- 추상 클래스 (몸통x)

public interface Pet {
	public void FoodCall();
}

- 추상이라고 보면 됨

public class Dog extends Animal implements Pet {
	
	public Dog(String name) {super(name);}
	
	@Override
	public void cry() {
		System.out.println(name + "!" + name + "!");
	}
	
	@Override
	public void FoodCall() {
		System.out.println(name + ".........");
	}
}
public class Cat extends Animal implements Pet {
	
	public Cat(String name) {super(name);}
	
	@Override
	public void cry() {
		System.out.println(name + "~~~~~!!!!");
	}
	
	@Override
	public void FoodCall() {
		System.out.println(".........");
	}
}
public class Wolf extends Animal {
	
	public Wolf(String name) {super(name);}
	
	@Override
	public void cry() {
		System.out.println(name + "~~~~~~~~~~~~~~~~~~");
	}
}

 

2-I Java interface 파트 2

- 콜백 : 사용자가 버튼을 눌렀을 때, 앱을 사용하다가 홈 버튼을 눌렀을 때, 다운로드가 완료 되었을 때..

- 콜백 메소드는 보통 on~ 의 형태.

- 콜백을 정의한 인터페이스는 ~Listener의 형태

 

2-J Java interface 파트2 (실습)

public class HelloWorld {
	public static void main(String []args) {
		Browser browser = new Browser();
		browser.imgClick();
	}
}

 

- 사용자가 browser에서 이미지 클릭.

 

public class Browser implements OnDownloadListener{
	
	public void imgClick() {
		Downloader loader = new Downloader(this);
		loader.start();
	}
	
	@Override
	public void onDownFinish() {
		System.out.println("Browser : onDownFinish()");
	}
	
	@Override
	public void onDownFailed() {
		
	}
}

- imgClcik에서 Downloader 클래스 만들고, this는 인터페이스(OnDownloadListener)를 넘겨준다.

- 넘겨주려면 OnDownloadListener에 있는 메소드들을 반드시 작성해줘야 함. (OnDownFinish, OnDownFailed)

 

public interface OnDownloadListener {
	public void onDownFinish();
	public void onDownFailed();
}

- 인터페이스 안에는 몸이 없음

 

import java.lang.Thread;
import java.lang.InterruptedException;

public class Downloader {
	
	private OnDownloadListener mListener;
	
	public Downloader(OnDownloadListener listener) {
		mListener = listener;
	}
	public void start() {
		System.out.println("Download Start");
		try {
			Thread.sleep(5000);
		}
		catch (InterruptedException e) {
			System.out.println(e.getMessage());
		}
		// callback
		mListener.onDownFinish();
	}
}

- mListener는 객체에서 갖고 있는 변수. 생성자 안의 변수를 사라지지 않도록 받음.

- 다 완료되면 콜백

 

2-K Java 2번째 세뇌의 시간

- 클래스, 상속, 인터페이스, 예외처리

- 클래스 : 객체를 만드는 청사진. public class Human / Human(클래스) me(객체) = new Human();(생성자)

- 상속: 클래스는 단 하나의 부모만 가질 수 있다. 부모는 조부모를 가질 수 있다.

     ex) public class Animal extends Life / public class Human extends Animal

- 인터페이스 : 클래스 하나에 1개 이상 구현 가능 (다중 상속) / 콜백 메소드 만들 수 있다.

    ex) public class Human extends Animal implements Programmer, Gamer, FoodFighter

- 예외처리 : try로 시도하고, catch로 대응

 

다음 강의부터 본격적으로 안드로이드 시작!

'MOBILE > Android' 카테고리의 다른 글

안드로이드 세뇌교실 4  (0) 2020.10.12
안드로이드 세뇌교실 3  (0) 2020.10.11
안드로이드 세뇌교실 1  (0) 2020.10.11