'생성자'에 해당되는 글 2건

  1. 2012.07.28 상속, 생성자
  2. 2012.07.28 클래스, 생성자

* 상속(Inheritance) : 기존의 class에 정의된 변수나 메소드를 재사용하여 새로운 class를 만드는것(물려받는것.- 확장성이 좋아짐)
->객체간의 상속

 

하나의 클래스에서 똑같은 코드를 물려 받아서 사용하는것.
부모-자식 관계

* 객체지향의 장점
1. 확장성
2. 재사용성
3. 유지보수

 

개 : 이름, 성별, 무게, 나이 , 색, 종, 키
      짖는다(),배설한다(),먹는다(),잔다()
고양이 :  이름, 성별, 무게, 나이, 종, 색, 키
  운다(), 배설한다(), 핱힌다(), 먹는다(), 잔다()
사람 : 이름, 나이, 성별, 무게, 키, 국적, 혈액형
          잔다(), 먹는다(), 말한다(), 일한다(),

동물 :  이름, 성별, 무게, 나이, 키
           먹는다(), 배설한다(), 잔다()

* 개, 고양이, 사람은 동물이기에 공통적인 속성을 동물에게 상속받는다.

물려주는 동물 class를 부모(super)class라 하고
물려받는 개, 사람, 고양이는 자식(sub)class라 한다.

* 상속 : is a 관계
-개(서브class) is a 동물(super class)
  개는 동물이다.
- 동물이면 개다.(x)

----------동물-----------
|                         -개 --           |
|                         |        |            |
|                         -----            |
-------------------------

- 동물의 type > 개의 type
   부모 type > 자식 type

* 상속 관계 일때만 type을 부모가 자식보다 type이 크다고 할수 있다.
(다형성에서 부모type이 자식type 보다 더 크다는 것을 사용한다.)
(부모는 추상적, 자식은 구체적)

* 추상화 :  공통점을 뽑아 내는것.(공통적인 것을 뽑아내서 새로운 것을 만들어 내는것.)
(고양이와, 개에 종과, 색이 공통적으로 있지만 사람에 없기때문에 동물로 빼낼 수 없다.)

* 다중 상속 : 부모class를 여러개 갖는것.
* 단일 상속 :  부모class를 하나만 갖는것.

* 자바는 단일 상속을 지원한다. ->class간의 상속을 할 시에는 단일 상속을 지원한다. (여러개의 상속을 하기 위해서는 interface를 지원한다)

동물                                                어류
키, 나이, 성별, 이름
먹는다(), 잔다()                          헤엄친다(), 먹는다()
           ^                                                   ^
           |                                                    |
           ---------------------------
   사람
   국적, 혈액형
   생각한다(), 말한다()

* 다중상속을 하면 상속에 상속을 갖는 구조가 되어 중복되는 메소드가 생겨 오류가 생길 수 있다.
(설계시 코드가 복잡하고 못쓰는 메소드가 생길 수 있어서 자바는 다중 상속을 지원하지 않는다. )

anmal(super class)
 ^
 | (상속)
Human(sub class)

- 코드구현

public class Animal {}
public class Human extends Animal{}

[제한자]class 식별자 extends 부모class이름{ 구현 }

* 상속되어 있는 부모 class가 없으면 object class(최상위 class)가 보이진 않지만 java.lang.Object가 상속되어 있다.
public class Animal extends Object{}

*사람으로 따지면 단군할아버지다.
-Object class에는 속성은 없고 메소드만 가지고 있다. ex :  toString(){}

*
Employee(직원)
-------------
+ id : String
+ name : String
+ salary : int
-------------
+getDetails() : String


Manager(관리자)
--------------
+ id : String
+ name : String
+ salary : int                                             //id,name,dalary,getDetails()는 직원의 것을 가져다 쓴다.
+department : String
---------------
+getDetails() : String


project : day15
package : inheritance.member
class : Employee
    Manager


//MemberTest.java

package inheritance.member;

/*public class MemberTest {
 public static void main(String[] args) {
  Employee emp = new Employee();
  emp.id = "emp-111";
  emp.name = "홍길동";
  emp.salary = 10000000;
  
  String str = emp.getDetails();
  System.out.println(str);
  
  
  Manager man = new Manager();
  man.id = "man-111";
  man.name = "이순신";
  man.salary = 2000000;
  man.department = "개발부";
   str = man.getDetails();
  System.out.println(str);
 }
}
*//*
public class MemberTest {
 public static void main(String[] args) {
  Employee emp = new Employee();
  emp.setId("emp-111");
  emp.setName("홍길동");
  emp.setSalary(10000000);
  
  String str = emp.getDetails();
  System.out.println(str);
  
  
  Manager man = new Manager();
  man.setId("man-111");
  man.setName("이순신");
  man.setSalary(2000000);
  man.department = "개발부";
  str = man.getDetails();
  System.out.println(str);
 }
}
*/
public class MemberTest {
 public static void main(String[] args) {
 Manager m = new Manager("m-111","이순신",200000,"영업부");
 String str = m.getDetails();
 System.out.println(str);
 }
}

 

//Manager.java

package inheritance.member;

public class Manager extends Employee{
 public String department;
 
 public Manager(){}
 public Manager(String id, String name, int salary, String department){
  
//  this.id = id;
//  this.name = name;
//  this.department = department;
  
  super(id,name,salary);
  this.department = department;
  
 }
 public String getDetails(){
  return  this.getClass().getSimpleName()+"[id=" + super.getId() + ", name=" + super.getName() + ", salary=" + super.getSalary()+" department = "+department+ "]";
  
 }
}


//Employee.java

package inheritance.member;

public class Employee {
 private String id;
 private String name;
 private int salary;
 
 //생성자
 public Employee(String id, String name, int salary){
  this.id = id;
  this.name = name;
  this.salary = salary;
 }
 public Employee(){}  //습관적으로 no-argument 생성자를 만들어라
 public String getDetails() {
  return this.getClass().getSimpleName()+"[id=" + id + ", name=" + name + ", salary=" + salary+ "]";
 }
 public String getId() {
  return id;
 }
 public void setId(String id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getSalary() {
  return salary;
 }
 public void setSalary(int salary) {
  this.salary = salary;
 }
 
}

 

'프로그래밍 > JAVA프로그래밍' 카테고리의 다른 글

final변수  (0) 2012.07.28
this, super키워드  (0) 2012.07.28
싱글턴 패턴  (0) 2012.07.28
static 예  (0) 2012.07.28
staticTest[실습]  (0) 2012.07.28
Posted by 조은성
,

5.class

한 파일(ABC.java)에
class A{
 }
class B{
 }
로 저장을 하면 class파일은 A.class B.class 두개가생긴다.

6. 생성자(Constructor) - 객체가 생성될 때 한번 호출되어 실행되는 동작.객체가 생성되서 소멸될 때까지 딱 1번만 실행됨
- 호출 : new 생성자()

- 구문 : [제한자] class이름([매개변수,...]){구현}
- 제한자 : public, protected, private : 접근제한자
- return 타입이 없다.
- 이름 :  class 이름과 반드시 같아야 한다.
- 매개변수(parameter)는 0~n개 가질 수 있다.

- default 생성자 : class에 생성자가 한개도 없으면 compiler가 생성해 주는 생성자
구문 : public Class이름(){}

- 생성자 역할 :  instance Member 변수의 값을 초기화(처음 값을 대입)
- 객체가 소멸될때까지 계속 사용할 자원들을 생성.

'프로그래밍 > JAVA프로그래밍' 카테고리의 다른 글

this  (0) 2012.07.28
오버로딩(overloading)  (0) 2012.07.28
editplus 다운로드 및 설치하기  (0) 2012.07.28
자바의 특징(키워드, 주석, 객체)  (0) 2012.07.28
자바의 역사 및 설치하기  (0) 2012.07.28
Posted by 조은성
,