'java super'에 해당되는 글 1건

[Java] Super()의 이해

[java] 2019. 12. 23. 14:48

[Java] Super()의 이해

- Super() 부모의 요소를 접근 하기 위해서 사용. 

  - 클래스 생성자 , public 변수,  public 함수의 접근이 가능함.


 

- ParentClass를 생성 후, ChildClass의 상속하는 구조.


1. Parent와 Child 클래스

ParentClass 클래스

package parent;

public class ParentClass {
	// private 요소 
	private String mother;
	private String father;
	// public 요소
	public String car = "BMW";
	
	// 빈 생성자 
	public ParentClass() {
		this.mother = "ParentMother";
		this.father = "ParentFather";
	}
	
	public ParentClass(String mother , String father) {
		this.mother = mother;
		this.father = father;
	}
	
	public String toString() {
		return "Parent = > " + this.father + " / " + "Parent = > " + this.mother; 
	}
	
	public String getFather() {
		return father;
	}
	
	public String getMother() {
		return mother;
	}
}

 

 

 

ChildClass 클래스

package child;

import parent.ParentClass;

public class ChildClass extends ParentClass {

	private String daughter;
	private String son;
	
	// 자식의 요소에만 값 할당, 부모의 요소는 접근하지 않음.
	public ChildClass(String daughter, String son) {
		this.daughter = daughter;
		this.son = son;
	}

	// 자식 요소와 부모 요소에 접근. 
	public ChildClass() {
		// 부모의 생성자를 호출하여 사용.
		super("ChildDaughter", "ChildSon");
		// 부모의 public 변수에 접근하여 값 변경
		super.car = "K7";
		
		// 자식의 요소의 값 할당 
		this.daughter = "not";
		this.son = "not";
	}

	public String toString() {
		return "Child = > " + super.getFather() + "/" + "Child = > " + super.getMother() + "/" + "Child = > "
				+ this.daughter + "/" + "Child = > " + this.son + "/" + "car = > " + super.car;
	}
}

2. Main Class

import child.ChildClass;

public class Main {

	public static void main(String[] args) {
		
		System.out.println("부모 Class 그대로 사용");
		ChildClass child1 = new ChildClass("Main1" , "Main2");
		System.out.println(child1.toString());
		
		System.out.println("부모 Class 초기화(Super()) 사용");
		ChildClass child2 = new ChildClass();
		System.out.println(child2.toString());		
	}

}

3. 결과화면

 

블로그 이미지

미나미나미

,