day10_MyMathTestEx08

육희영·2021년 10월 26일
0

static 개념정리2

package com.java1.day10;
//static 의 개념 정리
//static 이 붙은 변수는 new 클래스명 () 으로 클래스를 생성하지 않고 쓸수있다.
//static 이 붙지 않은 변수는 반드시 new 클래스명() 으로 클래스를 생성한뒤에 쓸수있다.
class MyMath2 { 
    long a, b; //인스턴스 변수
    static int c; //클래스 변수, 공유변수, static 변수
    // 인스턴스변수 a, b를 이용한 작업을 하므로  매개변수가 필요없다. 
    long add() {       return a + b; } 
    long subtract() {       return a - b; } 
    long multiply() {       return a * b; } 
    double divide() {       return a / b; } 

    // 인스턴스변수와 관계없이 매개변수만으로 작업이 가능하다. 
    static long add(long a, long b) {       return a + b; } 
    static long subtract(long a, long b) {       return a - b; } 
    static long multiply(long a, long b) {       return a * b; } 
    static double divide(double a, double b) {       return a / b; } 
} 

public class MyMathTestEx08 {
	public static void main(String[] args) {
		// 클래스메서드 호출  // 클래스 매서드? --> static 으로 선언된 매서드
		System.out.println(MyMath2.c);
        System.out.println(MyMath2.add(200L, 100L)); 
        System.out.println(MyMath2.subtract(200L, 100L)); 
        System.out.println(MyMath2.multiply(200L, 100L)); 
        System.out.println(MyMath2.divide(200.0, 100.0)); 
        System.out.println("--------------");
        
        MyMath2 mm = new MyMath2(); 
        mm.a = 200L; 
        mm.b = 100L;
        mm.c = 200;	// static 으로 선언된 변수는 인스턴스객체에서도 당연히 접근 할수 있다. mm.c 보다는 MyMath2.c 권장
        System.out.println(mm.c);	//mm.c 보다는 아래처럼 MyMath2.c를 권장한다.	
        System.out.println(MyMath2.c);
        // 인스턴스메서드는 객체생성 후에만 호출이 가능함. // 인스턴스 매서드? --> static 이 없는 매서드
        System.out.println(mm.add()); 
        System.out.println(mm.subtract()); 
        System.out.println(mm.multiply()); 
        System.out.println(mm.divide()); 
	}
}

출력결과

0
300
100
20000
2.0
--------------
200
200
300
100
20000
2.0

0개의 댓글

관련 채용 정보