개발입문/JAVA

[30일코딩] Inheritance 상속

haloaround 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());    

    }

}