Method Overriding

 

부모로 부터 물려받은 메서드를 재정의 하는것!

(같은 이름의 메서드)

 

package chapter3;

public class Computer {
	private String manufacturer;
	private String processor;
	private int ramSize;
	private int diskSize;
	private double processorSpeed;
	
	public Computer(String man,String proc,int ram,int disk,double procSpeed) {
		manufacturer = man;
		processor = proc;
		ramSize = ram;
		diskSize = disk;
		processorSpeed = procSpeed;
	}
	
	public double computePower() {
		return ramSize * processorSpeed;
	}
	public double getRamSize() {
		return ramSize;
	}
	public double getProcessorSpeed() {
		return processorSpeed;
	}
	public int getDistSize() {
		return diskSize;
	}
	
	public String toString() {
		String result = "manufacturer: " + manufacturer +
				"\nprocessor: " + processor +
				"\nramSize: " + ramSize +
				"\ndiskSize: " + diskSize +
				"\nprocessorSpeed: " + processorSpeed;
		return result;
	}
}

 

Computer 클래스의 toString() 메서드를 

Notebook클래스에서 재정의하고 싶다!

 

package chapter3;

public class Notebook extends Computer {
	
	public double screenSize;
	public double weight;
	
	public Notebook(String man,String proc, int ram, int disk, double speed, double screen, double weight){
		super(man,proc,ram,disk,speed);
	
		screenSize = screen;
		this.weight = weight;
	}
	public String toString() {
		String result = 
				super.toString()+
				"\nscreenSize: " + screenSize+
				"\nweight: " + weight;
		return result;
	}

	public static void main(String[] args) {
		Notebook test = new Notebook("Dell","15",4,1000,3.2,15.6,1.2);
		
		System.out.println(test.toString());

	}

}

Computer 클래스의 멤버가 private 이기때문에 직접 액세스 할 수 가없기에

super.toString()을 불러왔다.

만약 protect 접근제어자 였다면 직접 액세스가 가능하게 된다.!

'알고리즘 with 자바 > 자료구조' 카테고리의 다른 글

스케줄러 프로그램  (0) 2021.07.01
상속 3  (0) 2021.06.30
상속 1  (0) 2021.06.29
static 그리고 public 2  (0) 2021.06.28
static 그리고 public 1  (0) 2021.06.28

+ Recent posts