목차
•
public : 접근을 제한이 없음
•
private : 자기 자신의 클래스 내에서만 접근이 가능
•
default : 아무런 접근 제한자를 명시하지 않으면 default 값이 되며, 동일한 패키지 내에서만 접근이 가능
•
protected : 동일한 패키지 내에 존재하거나 파생클래스에서만 접근 가능
•
정보 은닉 : 변수에 private를 붙여 다른 클래스에서 수정 할 수 없게 변수를 보호
상속
class Car {
int speed; // 속도
public void setSpeed(int speed) { // 속도 변경 메소드
this.speed = speed;
}
}
public class ElectricCar extends Car {
int battery;
public void charge(int amount) { // 충전 메소드
battery += amount;
}
}
public class ElectricCarTest {
public static void main(String[] args) {
ElectricCar obj = new ElectricCar();
obj.speed = 10; // 부모 멤버 사용
obj.setSpeed(60); // 부모 멤버 사용
obj.charge(10); // 추가된 메소드 사용
}
}
Java
복사
•
부모 클래스(상위 클래스)를 상속 받아 그대로 사용
•
상속 목적 :
1) 이미 마련되어 있던 클래스를 재사용해서 효율적
2) 중복되는 코드를 줄이며 개발 시간 절약
상속과 생성자
class A {
public A() {
System.out.println("생성자 A");
}
}
class B extends A {
public B() {
System.out.println("생성자 B");
}
}
class C extends B {
public C() {
System.out.println("생성자 C");
}
}
public class Main {
public static void main(String[] args) {
C c = new C();
}
}
/* 결과값
생성자 A
생성자 B
생성자 C
*/
Java
복사
•
생성자 호출 순서
최상위 부모 클래스 —> 자식 클래스 순으로 호출 된다.
•
컴파일러는 부모 클래스의 기본 생성자가 자동 호출 한다.
명시적인 생성자 호출 - super();
class A {
public A() {
System.out.println("생성자 A");
}
}
class B extends A {
public B() {
super(); // 부모 생성자 호출
System.out.println("생성자 B");
}
}
Java
복사
•
super() : 부모 클래스 생성자 호출
묵시적인 생성자 호출 - super();
class A {
public A() {
System.out.println("생성자 A");
}
}
class B extends A {
public B() {
//super(); // 부모 생성자 호출
System.out.println("생성자 B");
}
}
Java
복사
•
개발자가 class B 처럼 super() 을 생성하지 않아도 컴파일러가 알아서 넣어준다.
부모클래스 생성자 선택
class A {
int x, y;
public A() {
x = y = 0;
}
public A(x, y) {
System.out.println(this.x + this.y);
}
}
class B extends A {
public B(int x, int y) {
super(x, y);
}
}
public class Main {
public static void main(String[] args) {
B b = new B();
}
}
Java
복사
•
개발자가 class B 처럼 super() 을 생성하지 않아도 컴파일러가 알아서 넣어준다.
•
메소드 오버라이딩
메소드 오버라이딩 예제 1) 연습문제
class Shape {
public void drwa() {
System.out.println("도형을 그립니다.");
}
}
class Rectangle extends Shape {
public void draw() {
System.out.println("사격형을 그립니다.");
}
}
public class Main {
public static void main(String[] args) {
Shape shape = new Shape();
shape.drwa();
Rectangle rectangle = new Rectangle();
rectangle.draw();
}
}
Java
복사
•
자식 클래스가 부모 클래스의 메소드를 자신의 필요에 맞추어 재정의
•
함수 바디만 달리 하여야함
메소드 오버라이디 예제 2) 미니 프로젝트
class Employee{
private int salary;
public Employee() {
salary = 3000000; //기본급
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}
class Manager extends Employee{
public Manager() {
super.setSalary(super.getSalary() + 200000);
}
@Override
public int getSalary() {
return super.getSalary();
}
}
class Programer extends Employee{
public Programer() {
super.setSalary(super.getSalary() + 300000);
}
@Override
public int getSalary() {
return super.getSalary();
}
}
public class Test {
public static void main(String[] args) {
Manager manager = new Manager();
System.out.println(manager.getSalary());
Programer programer = new Programer();
System.out.println(programer.getSalary());
}
}
Java
복사
메소드 오버로딩
메소드 오버로딩 예제
class OverloadingTest{
//이름이 cat인 메서드
void cat(){
System.out.println("매개변수 없음");
}
//매개변수 int형이 2개인 cat 메서드
void cat(int a, int b){
System.out.println("매개변수 :"+a+", "+b);
}
//매개변수 String형이 한 개인 cat 메서드
void cat(String c){
System.out.println("매개변수 : "+ c);
}
}
public class OverTest {
public static void main(String[] args) {
//OverloadingTest 객체 생성
OverloadingTest ot = new OverloadingTest();
//매개변수가 없는 cat() 호출
ot.cat();
//매개변수가 int형 두개인 cat() 호출
ot.cat(20, 80);
//매개변수가 String 한개인 cat() 호출
ot.cat("오버로딩 예제입니다.");
}
}
Java
복사
•
오버로딩 : 같은 이름의 함수(메서드)를 여러개 정의하고, 매개변수의 유형과 개수를 다르게 하여 다양한 유형의 호출에 응답 가능
다형성 (Polymorphism)
다형성 예시 1)
class People {
public void printInfo() {
System.out.println("나는 사람입니다.");
}
}
class Man extends People {
@Override
public void printInfo() {
super.printInfo();
System.out.println("그리고 나는 남자입니다.");
}
}
class Woman extends People {
@Override
public void printInfo() {
super.printInfo();
System.out.println("그리고 나는 여자입니다.");
}
}
public class Main {
public static void main(String[] args) {
People people = new Man();
people.printInfo();
System.out.println();
people = new Woman();
people.printInfo();
}
}
/* 실행 결과
나는 사람입니다.
그리고 나는 남자입니다.
나는 사람입니다.
그리고 나는 여자입니다.
*/
Java
복사
•
업캐스팅 & 다운캐스팅
•
instanceof 연산자로 객체 실제 타입 확인
다형성 예시 2)
// 다형성의 이해
// 1. 다형성이 적용되면 부모 = 자식
// 2. 다형성에서 오버라이딩은 자식의 것.
class Shape {
public Shape() {
System.out.println("도형입니다.");
}
public void draw() {
System.out.println("도형을 그립니다.");
}
}
class Rectangle extends Shape {
public Rectangle() {
System.out.println("사각형 생성자");
}
@Override
public void draw() {
System.out.println("사각형 도형을 그립니다.");
}
}
class Triangle extends Shape {
public Triangle() {
System.out.println("삼각형 생성자");
}
@Override
public void draw() {
System.out.println("삼각형 도형을 그립니다.");
}
public void draw2() {
System.out.println("삼각형 도형을 그립니다.");
}
}
// 다형성의 활용
//
public class Poly {
public static void main(String[] args) {
// Shape shape = new Shape();
// shape.draw();
//
Rectangle rectangle = new Rectangle();
rectangle.draw();
rectangle.draw2();
// // 다형성(polymorphism)
// shape는 부모 여기는 자식. 형변환 해줘야함. 어떻게 ? new 앞에 (Shape). 부모타입에 객체를 자식으로 넣게 되면 자동적으로 컴파일 된다.
Shape shape2 = new Rectangle();
shape2.draw();
// shape2.draw2(); // 이건 안됌. s의 데이터 타입은 shape 클래스에는 draw2 메서드를 포함하고 있지 않기 때문.
shape2 = new Triangle();
shape2.draw(); // sub(자식)이 호출되고 있음.
// Rectangle rec = new Shape(); // 에러. 왜? 이게 다형성의 가장 중요한 부분
// 이거는 자식 = 부모임. 이건 안된다.
// int num = 3.0; 이거랑 같은 것.
}
}
Java
복사