클래스와 인스턴스

sisun·2023년 4월 18일
0

백엔드 연습

목록 보기
6/6

로직을 메소드에 도입하는 예제

public static void sum(int left,int right) {
		System.out.println(left + right);
	}
	
	public static void main(String[] args) {
		sum (10,20);
		sum (20,40);
	}
}

로직을 메소드에 도입하는 예제 2

public static void avg(int left, int right) {
		System.out.println((left + right) /2);
	}
	
	public static void sum(int left, int right) {
		System.out.println(left + right);
	}
	
	public static void main(String[] args) {
		int left, right;
	
#		left = 10;
#		right = 20;
#		//이 중간에 사이가 멀어지면 알아보기 힘들 수 있다.
#       //그래서 객체지향 언어가 등장함
#		sum (left,right);
#		avg (left,right);    //#연관되어있는 것
		
		left = 20;
		right = 40;
		
		sum (left,right);
		avg (left,right); //#부터 여기까지 반복
	}
}

객체와 인스턴스 , 메소드

package name;

class Calculator{ //지금부터 Calculator라고 하는 객체를 알려주겠다
	int left, right;
	
	public void setOprands(int left, int right) {
		this.left = left;
		this.right = right; //밑에 c1.setOprands(10, 20);
		//this. 은 c1에 담겨있는 인스턴스를 가르키는것 위쪽 "int left,right를 가리킴
	}
	public void sum() {
		System.out.println(this.left+this.right);
	}
	public void avg() {
		System.out.println((this.left + this.right)/2); //여기까지 설계도
		}
	}
	public class CalculatorDemo2{
		
		public static void main(String[] args) {
			
			Calculator c1 = new Calculator(); 
			//처음 Calculator 클래스에 해당됨, new를 통해서 실제 객체를 만들 설계도가 위쪽부터 있음
				c1.setOprands(10, 20); //이 c1이라는 객체는 위에 setOprands를 가리킴
				c1.sum(); //위에 c1를 가리킴
				c1.avg();
				
				Calculator c2 = new Calculator();
				// new Calculator(); 를 통해 인스턴스 생성 후 c2변수에 담김
				c2.setOprands(20, 40);
				// 인스턴스 안에 left 20, right 40이 담김
				c2.sum(); 
				// 인스턴스 left + right 값 (60)
				c2.avg();
				// 인스턴스 ((left + right)/2) 값 (30)
			}
		}
profile
풀스택 국비수강중

0개의 댓글