-
[30일코딩] Inheritance 상속개발입문/JAVA 2017. 5. 7. 00:20
상속 Inheritance
Inheritance... 상속은
defines the relationship between the superclass and the subclass.
부모클래스와 자식클래스 간의 관계
- parent superclass has the traits originally
- child subclass inherits the traits
- Everything created as a class inherit the Object class.
public / private 접근제어자
private int age;
다른 클래스에서 접근 불가능합니다. :)
대신 getter/setter 메소드로 접근 가능합니다.
public int getAge() {
return age;
}
public void setAge() {
this.age = age;
}
예시
import java.util.Locale;
import java.text.NumberFormat;
class Employee {
// instance variables:
protected String name;
private int salary;
// implicit & explicit constructor
Employee() {
}
Employee(String name){
// use name param to initialize instance variable:
this.name = name;
}
// getter & setter method
String getName(){
return name;
}
void setSalary(int salary){
this.salary = salary;
}
int getSalary(){
return salary;
}
// instance method
void print(){
if(this.salary == 0){
System.err.println("Error: No salary set for " + this.name
+ "; please set salary and try again.\n");
}
else{ // Print employee information
// Formatter for salary that will add commas between zeroes:
NumberFormat salaryFormat = NumberFormat.getNumberInstance(Locale.US);
System.out.println("Employee Name: " + this.name
+ "\nSalary: " + salaryFormat.format(this.salary) + "\n");
}
}
}
class Volunteer extends Employee{
// instance variable
int hours;
// Default Constructor
Volunteer() {
}
// Parameterized Constructor
Volunteer(String name){
super(name);
}
// getter & setter Method
int getHours(){
return hours;
}
void setHours(int hours){
this.hours = hours;
}
// Override the method of super class
void print(){
System.out.println("Volunteer Name: " + this.getName()
+ "\nHours: " + this.getHours());
}
}
'개발입문 > JAVA' 카테고리의 다른 글
[30일코딩] 범위 Scope (0) 2017.05.07 [30일코딩] Abstract Class 추상클래스 (0) 2017.05.07 [30일코딩] Class 구조 (0) 2017.05.06 [30일코딩] Binary Numbers 2진법 (0) 2017.05.06 [30일코딩] Recursion (0) 2017.05.06