728x90
반응형

-상속자-

모든 생성자의 첫 번째 줄에는 super() 소스코드가 생략되어 있다.

단, 생성자의 첫 번째 줄에 super() 또는 this()가 선언된 경우 super() 소스코드는 추가되지 않는다.

 

객체간의 관계

is a관계 : 상속관계

has a관계 : 어떤 클래스에서 다른 클래스의 주소를 멤버변수로 가진것

 


class A{

  A(){ 
    
    System.out.println(1); 
  
  } // B 클래스 객체 생성해서 생성자 method B를 실행하면

} // 부모 클래스 A의 생성자를 불러와 같이 실행하게 된다 하지만 이때



class B extends A{ // 생성자의 첫 번째 줄에는 super() 소스코드가 생략되어있으며

  B(){ 
    
    super() 
    
    System.out.println(2); 
  
  } // super()의 매개변수 타입과 부모 클래스의 생성자의 매개변수 타입이

} // 일치해야 부모 클래스의 생성자를 불러올 수 있다



class C { // 결과는 1, 2가 출력된다

  public static void main(String[] args){

    B o=new B();

  } 

}


 

 

-super()-

super()는 일반 생성자에 생략이 되어있다

평소에는 어떠한 작동을 하지않고 상속관계가 되었을때에만 작동이된다

 

상속관계에서 super()로 인해 부모 클래스에 해당하는 생서자를 불러오게된다

 


class A{

  A(String s){

    System.out.println(1);

  }
}



class B extends A{

  B(){ 
  
    this(100); 
  
  } // this()는 자기 자신의 생성자를 불러오는 코드로써 this()의 매개변수 타입과

  B(int a){ 
  
  	super("aaa"); 
    
  } // 불러올 생성자의 매개변수 타입을 일치시킨다. 이때 동일시 된 생성자가

} // 실행되고 실행문에 supe()에 의해 부모 클래스에 해당하는 생성자를





class C{ // 불러오게 되는데 이때도 매개변수의 타입이 일치해야지만 부모 클래스의 생성자를 불러올 수 있다

  public static void main(String[] args){

    B o=new B();

  }
}

=========================================================================================


class Animal{

  String type;
  
  Animal(String t){ 
  
  type=t; 
  
  }
}


class Dog extends Animal{

  Dog(){
  
    super("개");		
      // 상속자 관계에서 부모 클래스에서 생성자 method가 선언되어있고 매개변수도 선언되어있다면 
  }	  // 부모 클래스의 생성자 매개변수와 자식 클래스의 생성자 super의 기본타입이 같지 않다면
}	  // 컴파일에러가 일어나기 때문에 부모의 생성자 method 매개변수 타입이 같은지 확인하고 
	  // super()을 꼭 이용하여야만 에러를 방지하고 사용할 수 있다

class Cat extends Animal{	
  Cat(){
    super("고양이");
  }
}


class A{
  public static void main(String[] args){
    Dog dog=new Dog();
    Cat cat=new Cat();
    System.out.println(dog.type);	// 개
    System.out.println(cat.type);	// 고양이
  }
}
 

 

여기서  this란

아래의 예문으로 확인하여 익히자

 

-this, this()-


class Car{
  String color="red";
    void print(){ 
        				// this 자체가 멤버변수를 의미한다. 즉, this. 멤버변수를 실행하면
      System.out.println(this.color); 	// 멤버변수의 값을 얻을 수 있다
 	}			
}


class A{
	public static void main(String[] args){
		Car car1=new Car();  
		Car car2=new Car();
		Car car3=new Car();
		car1.print();
		car2.print();
		car3.print();
	}
}

--------------------------------------------------------------------------------------------

class A{						    // 생성자의 method에서 this()를 이용하면 
	A(){ System.out.println(1); }	// 매개변수 타입이 서로 다른 자료형 타입이더라도 
    								// 출력할 수 있다
	A(String s){ 
      this(); 
      System.out.println(2); } 	
    
	A(int i){ 
      this("aa");  // 첫 로컬변수에 this(“aa“)로 매개변수 동일타입에 해당하는   
      System.out.println(3);  // 위치 이동하며 더 이상 동일한 타입이 없다면 실행 순서는 역순으로 진행
    }	
    
}		


class B{						
	public static void main(String[] args){		
		A o=new A(100);	// 처음 호출문에 생성자 객체생성으로 매개변수 정수 100으로 호출한다
	}
}



-------------------------------------------------------------------------------------------

class A{
	int n;
	A(int n){ this.n=n; }
	A getA(){ return this; }		
}


class B{
	public static void main(String args[]){
		A o1=new A(100);
        
		A o2=o1.getA();	    
        	// method getA()에서 return this를 불러와서 멤버변수의 값을 객체 생성한 o2에 저장하게 된다
		
        System.out.println(o1.n); // 100 
        
		System.out.println(o2.n); // 100
        	 // 객체생성 변수에 멤버변수 값 100 저장했기 때문에 o2.n을 불러들이면  100이 출력된다
	}						
}
  

 

 

 

-super, 은닉변수-

은닉변수를 설정하여 super을 이용해서 부모의 멤버변수를 불러올 수 있다


class Animal{

  int num=100; // 은닉변수(shadow variable) 사용하고 싶지 않다는 뜻

    void sound(){

      System.out.println("소리결정되지 않음");

    } 
}



class Dog extends Animal{

  int num=200; // 부모 클래스의 멤버변수와 이름이 같을 때 자식 멤버변수가 재할당된다

  void sound(){ // 그래서 부모 클래스의 멤버변수를 불러올 수 없다 하지만 super을 이용하여

    super.sound(); // 부모 멤버변수를 불러올 수 있다

    System.out.println(super.num);

    System.out.println(this.num);

    System.out.println(num);

    System.out.println("멍멍");

  } 
}



class A{

  public static void main(String[] args){

    Dog dog=new Dog();

    dog.sound();

  } 
}

// -결과-
// 소리 결정되지 않음
// 멍멍

 

 

이제 종합 예제 문제로 활용법을 알아보자


class Video{

  String title;
  
  Video(String t){ 
  
  title=t; 
  
  }
}


class GeneralMember{

  String name; 
  
  Video rentalVideo;
  
  GeneralMember(String n, Video v){
  
  name=n; 
  
  rentalVideo=v;
  
  }
}



class SpecialMember extends GeneralMember{

  int bonus;
  
  SpecialMember(String n, Video v, int b){
  
  super(n,v);
  
  bonus=b;
  
  }
}



class VideoShop{
 public static void main(String[] args){
	Video v1=new Video("슈렉");
	Video v2=new Video("겨울왕국");
	GeneralMember m1=new GeneralMember("홍길동",v1);
	SpecialMember m2=new SpecialMember("김길동",v2,100);
	System.out.println(m1.name); // 홍길동
	System.out.println(m1.rentalVideo.title); // 슈렉
	System.out.println(m2.name); // 김길동
	System.out.println(m2.rentalVideo.title); // 겨울왕국
	System.out.println(m2.bonus); // 100
 }
}

 

 


2020/06/02 - [Java/Java 입문] - Java - 생성자 호출과 선언, 개념

 

Java - 생성자 호출과 선언, 개념

생성자 기본 method 형식에서 클래스 변수로 method를 생성한 선언문이다 객체 생성할 때 매개변수 값을 동시에 선언하는 방식으로 식은 다음과 같다. ( 클래스 변수 식별자변수=new 클래스 변수(매��

tantangerine.tistory.com

 

728x90
반응형

+ Recent posts

Powered by Tistory, Designed by wallel