* MethodEx05.java -클래스 변수와 인스턴스 변수 / 클래스 메서드와 인스턴스 메서드 활용
classMethod{
Stringstr1="데이터1";
staticStringstr2="데이터2";
voiddoFunc1(){
System.out.println(str1);
System.out.println(str2);
}
staticvoiddoFunc2(){
//System.out.println(str1); //static함수 안에서는 인스턴스 변수를 사용하지 못함
System.out.println(str2);
}
}
publicclassMethodEx05 {
publicstaticvoidmain(String[] args){
Methodm=newMethod();
m.doFunc1();
//m.doFunc2();
Method.doFunc2(); //클래스 안에 있는 static 함수를 참조
}
}
* MethodEx06.java - 인스턴스 메서드 안에서 this로 인스턴스 메서드 참조
classMethod{
Stringstr1="데이터1";
voiddoFunc1(){
System.out.println(str1);
//this는 자기참조용 주소
System.out.println(this);
System.out.println(this.str1);
//doFunc2();
this.doFunc2();
}
voiddoFunc2(){
System.out.println("doFunc2() 호출");
}
}
//public static void main(String[] args) 설명
//java MethodEx06
// java= MethodEx06.main() 실행
publicclassMethodEx06 {
publicstaticvoidmain(String[] args){
Methodm=newMethod();
Methodm1=newMethod();
m.doFunc1();
System.out.println(m); //m은 참조값(주소)
System.out.println(m1);
m1.doFunc1(); //m과 m1에서 만들어진 doFunc1는 서로 다른 객체이기 때문에 this를 했을 때 주소값이 다르다.
System.out.println(m);
System.out.println(m1);
}
}
생성자 (Constructor)
- 객체의 레퍼런스를 생성하기 전에 객체의 초기화를 위해 사용되는 코드의 블록 (인스턴스 초기화) - 생성자의 이름 = 클래스의 이름 - 생성자는 return 값이 없다. - 생성자 안에서 다른 생성자를 호출할 때는 항상 첫줄에서만 호출해야 한다. - 연산자 new가 인스턴스를 생성하는 것이며 생성자가 인스턴스를 생성하는 것이 아니기 때문에 헷갈리면 안된다. => 메모리가 생성될 때 생성자도 호출이 가능하다.
* ConstructorEx01.java - 생성자의 기본구조
classConstructor{
//생성자의 메서드명은 클래스 이름과 같아야 한다
// 리턴이 없음
//컴파일러가 기본적으로 제공해왔기 때문에(기본생성자) 사용하지 않았던 것이다.
Constructor(){
System.out.println("생성자 호출");
}
}
publicclassConstructorEx01 {
publicstaticvoidmain(String[] args) {
// new Constructor();
// => Constructor() : 생성자 호출
Constructorc1=newConstructor();
//c1.Constructor(); 생성자를 따로 호출할 수 없다. 윗줄과 같이 메모리가 생성될 때 생성자도 호출이 가능하다.
}
}
* ConstructorEx02.java - 생성자 오버로딩
classConstructor{
Stringstr1;
//생성자 오버로딩: 생성자의 이름이 같아도 매개변수가 다르기 때문에 같은 이름을 사용할 수 있음
Constructor(){
System.out.println("생성자 호출");
str1="홍길동";
}
Constructor(Stringstr1){
this.str1=str1; //this는 인스턴스 멤버와 연관이 있기 때문에 변수이름이 같아도 참조하는 역할이 다름을 알 수 있다.
}
}
publicclassConstructorEx02 {
publicstaticvoidmain(String[] args) {
Constructorc1=newConstructor();
Constructorc2=newConstructor("손수빈");
System.out.println(c1.str1); //기본 생성자 Constructor을 출력
System.out.println(c2.str1); //따로 만든 생성자 Constructor(String str1)을 출력
* Ex6_13.java - 기본생성자와 매개변수가 있는 생성자(2) -> 매개변수가 있는 생성자를 기본 생성자에서 this로 참조해 사용할 수 있다 (반복되는 내용 혹은 적용할 내용이 있을 시) -> this.color 하면 인스턴스 변수이고, color은 생성자의 매개변수로 정의된 지역변수가 된다. ( 변수의 이름은 같지만 참조하는 내용이 달라진다) -> this로 생성자를 참조하는지 인스턴스 변수를 참조하는지에 정확히 확인해야 한다.
* InheritanceEx05.java - super super: 자식클래스 안에서 부모 클래스의 메서드를 호출하고 싶을 때 사용함
classParent{
voidviewParent(){
System.out.println("viewParent() 호출");
}
}
classChildextendsParent{
voidviewChild(){
System.out.println("viewChild() 호출");
}
//오버라이딩
voidviewParent(){
//부모 viewParent()
super.viewParent(); //super :자식 안에서 부모의 메서드를 호출하고 싶을 때 사용
System.out.println("child viewParent() 호출");
}
}
publicclassInheritanceEx05 {
publicstaticvoidmain(String[] args) {
Childc=newChild();
c.viewChild();
c.viewParent();
}
}
*InheritanceEx06.java - super(2)
classParent{
/* Parent(){
System.out.println("Parent 생성자 호출");
}
*/
Parent(Stringname){
System.out.println("Parent(String name)생성자 호출"); //부모 클래스가 먼저 인스턴스화 되는데 기본 생성자가 없기 때문에 Child에서 호출할 시 에러발생
}
}
classChildextendsParent{
Child(){
super("손수빈"); //부모의 생성자를 명시적으로 호출하고 싶을 때 super을 사용하여 호출가능하다.
System.out.println("Child생성자 호출");
}
}
publicclassInheritanceEx06 {
publicstaticvoidmain(String[] args) {
Childc=newChild();
}
}
* Ex7_3.java - this 와 super을 이용한 변수값 확인
classParent2{intx=10;}
classChild2extendsParent2{
intx=20;
voidmethod(){
System.out.println("x="+x);
System.out.println("this.x="+this.x);
System.out.println("super.x="+super.x);
}
}
publicclassEx7_3 {
publicstaticvoidmain(String[] args) {
Child2c=newChild2();
c.method();
}
}
* Ex7_4.java - this 와 super을 이용한 변수값 확인(2)
classPoint{
intx,y;
Point(intx, inty){
this.x=x; //Point 클래스 안에 있는 인스턴스 변수(x,y)를 this로 표현
this.y=y;
}
}
classPoint3DextendsPoint{
intz;
Point3D(intx,inty, intz){
super(x, y); //Point클래스를 상속받아 Point클래스 안의 Point생성자를 super로 사용
this.z=z; //Point3D 클래스 안에 있는 인스턴스 변수(z)를 this로 표현
}
}
publicclassEx7_4 {
publicstaticvoidmain(String[] args) {
Point3Dp=newPoint3D(1, 2, 3);
System.out.println("x="+p.x+",y="+p.y+",z="+p.z);
}
}
* InheritanceEx07.java - final final: 변수에 사용되면 값을 변경할 수 없는 상수가 되며, 메서드에 사용되면 오버라이딩을 할 수 없게된다. 클래스에 사용되면 자신을 확장하는 자손클래스를 정의하지 못하게 된다.
classParent{ //여기에 final을 붙이면 cannot inherit from final Parent라고 뜬다 (상속불가능)
StringDATA; //여기에 final을 붙이면 already have been assigned라고 뜨면서 처음 DATA만 적용이 된다.
Parent(){
System.out.println("Parent 생성자 호출");
this.DATA="10";
this.DATA="20";
System.out.println(this.DATA);
}
voidviewParent(){ // 여기에 final을 붙이면 cannot override viewParent() in Parent라고 뜬다 (오버라이딩 불가능)
System.out.println("Parent viewParent() 호출");
}
}
classChildextendsParent{
Child(){
System.out.println("Child생성자 호출");
}
voidviewParent(){
System.out.println("Child viewParent() 호출");
}
}
publicclassInheritanceEx07 {
publicstaticvoidmain(String[] args) {
Childc=newChild();
c.viewParent();
}
}
=> 어떤 변수인지 구분 할 수 있어야 한다. (인스턴스 변수, 클래스 변수, 지역변수)
=> 오버라이딩과 오버로딩에 대한 개념 확실하게 잡기
=> 상속 시 각 생성자의 주소값이 어떻게 되는지에 대해 이해 필요(주소가 왜 같게 나오는지)
변수 구분 정리 (시험문제 가능) 1. 클래스 변수 = Static변수 2. 인스턴스 안에 있는 변수가 인스턴스 변수 3. 인스턴스를 선언하는 변수는 main의 지역변수 4. 생성자 안에서 매개변수의 역할을 하는 변수는 지역변수
this 사용 정리 1. this : 인스턴스 자신을 가리키는 참조변수, 인스턴스의 주소가 저장되어 있다. 모든 인스턴스메서드에 지역변수로 숨겨진 채로 존재한다. 2. this(), this(매개변수) : 생성자, 같은 클래스의 다른 생성자를 호출할 때 사용한다.
오버로딩/오버라이딩 정리 1. 오버로딩 : 부모 클래스를 상속받으며 부모 클래스 안에 있는 메소드의 이름과 같은 메소드를 정의 매개변수의 형태나 개수가 다름 (매개변수의 형태에 따라 부모 메소드를 사용할지 안할지 정할 수 있음) 2. 오버라이딩: 부모 클래스를 상속받아도 자식 클래스에서 같은 형태(이름, 매개변수 동일)의 클래스를 재정의 하면 자식 메서드가 적용됨.