정적(클래스) 변수 & 메소드
public class Test
{
public int i; //객체변수
public static int j =0;
public void IncreaseI()
{
i++;
}
public void IncreaseJ()
{
j++;
}
public static int num = 0;
public Test() //기본생성자
{
num++;
}
public static int mtTest()
{
return num;
}
}
class MainClass
{
[STAThread]
static void Main(string[] args)
{
Test n1 = new Test();
Test n2 = new Test();
Test n3 = new Test();
Test n4 = new Test();
Test n5 = new Test();
Console.WriteLine(Test.num);
//num은 정적변수이기 때문에 객체를 생성될때마다 기본생성자가 실행되어 변경된 값을 그대로 적용받는다.
Console.WriteLine("객체생성전 : "+Test.j);
//static으로 선언하지 않았을경우에는 객체를 생성해서 사용한다.
//똑같은 이름의 객체를 생성한다 하더라도 새로 생성한 두 객체는 기본틀만 같을 뿐 각각 다른 객체이다.
Test t = new Test();
t.i = 100;
t.IncreaseI();
t.IncreaseI();
Test t2 = new Test();
t2.i = 200;
t2.IncreaseI();
t2.IncreaseJ();
Console.WriteLine("t.i = " + t.i);
Console.WriteLine("t2.i = " + t2.i);
Console.WriteLine("Test.j = " + Test.j);
// static으로 선언한 객체는 클래스명.객체명으로만 접근가능하다.
// 각 객체간의 공통된 데이터로 사용하고 싶을때 사용..
}
}
객체생성
- 클래스를 기반으로 객체를 생성
- 인스턴스화 or 객체생성
- new연산자 + 객체 생성자(Constructor)
this 연산자
- 객체 자신을 의미(메소드가 호출되는 객체자신)
- 정적 메소드에선 불가능(객체에서만 사용가능)
- this로 객체반환도 가능
public class Goods
{
private int price, quantity;
//private static int a;
public Goods SetPrice(int price)
{
this.price = price;
//this.a = price //정적변수는 this로 접근할수 없다.
return this; //SetPrice메소드의 리턴형태는 Goods
//위는 아래형태로 리턴하는것과 같다.
//Goods goods = new Goods();
//return Goods;
}
public Goods SetQuantity(int quantity)
{
this.quantity = quantity;
return this;
}
public int PutPirce()
{
return this.price;
}
public int PutQuantity()
{
return this.quantity;
}
}
public class callClass
{
public static void ReturnThis()
{
Goods product = new Goods();
product.SetPrice(100).SetQuantity(30);
//product.SetPrice(100);
//product.SetQuantity(30);
//위와 같은 형태
//product.SetPrice(100)의 리턴값이 Goods 이기때문에
//그다음에 실행해야 하는 문장은 product.SetQuantity(30);과 같다.
Console.WriteLine("가격은 : {0,3}원", product.PutPirce());
Console.WriteLine("갯수은 : {0,3}개", product.PutQuantity());
}
}