Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

Min's dev-log

[Exception 해결] NullPointerException 본문

Exception 해결

[Exception 해결] NullPointerException

minyy 2023. 6. 20. 00:03

[NullPointerException]

원인 : 메서드 수행 주체인 객체가 NULL인 상황 (아무것도 없는 NULL이 수행할수없다)

sc.nextInt()

rand.nextInt(10)

car.speedUp()

cat.hello()

=> sc, rand, car처럼 수행 주체인 객체가 있어야하는데 주체가 NULL이되면 안된다

=> equals를 쓸때는 NULL체크 로직을 체크해야한다!!!

 

▼ 예시 코드

class Animal{
	String name;
	String type;
	String tool;
	void action() {
		// 주체가 NULL이되면 안된다 
		// -> equals를 쓸때는 NULL체크 로직을 체크해야한다.!!!
		if(this.tool==null) {
			// 문자열끼리 비교할때는 
			// NULL 체크 로직을 최상단에 위치시켜야 NPE발생하지 않는다.
			System.out.println("나무 흔들기");
		}
		else if(this.tool.equals("도끼")) {
			System.out.println("나무베기");
		}
		else if(this.tool.equals("낚시대")) {
			System.out.println("낚시하기");
		}
		else if(this.tool.equals("삽")) {
			System.out.println("땅파기");
		}
		else {
			System.out.println("유효성 검사 - 잘못된도구");
		}
	}
	void hello() {
		System.out.println("안녕 ㅎㅎ");
	}
	Animal(String name){ // 인자1개 메인을 보고 예상한것
		this(name,null);
	}
	Animal(String name,String tool){ // 인자2개
		this.name=name;
		this.type="동물";
		this.tool=tool;
	}
	@Override
	public String toString() {
		return this.type+"주민 "+this.name+": "+this.tool;
	}
}
class Hamster extends Animal{
	@Override
	void hello() {
		System.out.println("안녕 찍찍");
	}
	Hamster(String name){
		this(name,null);
	}
	Hamster(String name,String tool){
		super(name,tool);
		this.type="햄스터";
	}
}
class Bird extends Animal{
	@Override
	void hello() {
		System.out.println("안녕 짹짹");
	}
	Bird(String name){
		this(name,null);
	}
	Bird(String name,String tool){
		super(name,tool);
		this.type="새";
	}
}
class Cat extends Animal{
	@Override
	void hello() {
		System.out.println("안녕 야옹");
	}
	Cat(String name){
		this(name,null);
	}
	Cat(String name,String tool){
		super(name,tool);
		this.type="고양이";
	}
}
public class Test02 {
	public static void main(String[] args) {

		Hamster ham=new Hamster("뽀야미","삽");
		// 뽀야미, 햄스터, 삽
		Bird bird=new Bird("문대"); // 인자 한개짜리
		// 문대, 새, x
		Cat cat=new Cat("1호","낚시대");
		// 1호, 고양이, 낚시대

		ham.action();
		bird.action(); 
		// tool을 null로 해놨기 때문에 -> this.tool.equals 
		// -> null.equals가 된다 -> 아무것도 없는 null이 수행 주체가 될순없다
		// => equals를 쓸때는 NULL체크 로직을 체크해야한다.!!!
		
		cat.hello();
		
		System.out.println(ham);
		
		Animal[] data=new Animal[3];
		data[0]=ham;
		data[1]=bird;
		data[2]=cat;
		
		for(Animal v:data) {
			v.hello();
			// 오버라이딩한 메서드가 자동호출되는 동적바인딩 현상이 일어났기 때문!
		}
	}
}

 

 

Comments