base 연산자로 상위 객체에 접근한다.class Person
{
...
}
class Student: Person
{
...
}
class StudentWorker: Studnet
{
...
}
Student 클래스 : Person을 상속 받는다.StudentWorker 클래스 : Student를 상속 받는다.class Person
{
string name;
int age;
public int GetAge() { return age; }
}
Person에 공통 부분을 정의하였다.class Student: Person
{
int id;
}
class Researcher: Person
{
string research;
}
Student와 Researcher에 필요한 멤버를 추가하였다.class Person
{
string name;
int age;
}
class Student: Person
{
int id;
...
}
Student s = new Student();s ⇒ name | age | idpublic class Point
{
private int x, y;
public void Set(int x, int y)
{
this.x = x;
this.y = y;
}
public void ShowPoint()
{
Console.WriteLine("x + y");
}
}
public class ColorPoint: Point
{
private string color;
public void ShowColorPoint()
{
Console.WriteLine(color);
ShowPoint();
}
}
Point를 상속받은 ColorPoint 선언ShowColorPoint() : 컬러 점의 좌표 출력ShowPoint() : Point 클래스의 ShowPoint() 호출public class ColorPointApp
{
static void Main(string[] args)
{
ColorPoint cp = new ColorPoint();
cp.Set(3,4);
cp.SetColor("Red");
cp.ShowColorPoint();
}
}
cp.Set(3,4) : Point 클래스의 Set() 메서드 호출cp.SetColor("Red") : 색 지정cp.ShowColorPoint() : 컬러 점의 좌표 출력protected와 public으로 지정된 멤버만을 상속class Person
{
int age;
protecte String name;
public int height;
private int weight;
public int GetAge()
{
return age;
}
public void SetAge(int age)
{
this.age = age;
}
public int GetWeight()
{
return weight;
}
public void SetWeight(int weight)
{
this.weight = weight;
}
}
Person 클래스의 private 필드인 age, weight는 Student 클래스에서 접근이 불가능하여 부모 클래스인Person의 public 메소드를 통해서만 조작 가능하다.public class Student: Person
{
int id;
public int GetID()
{
return id;
}
void Set()
{
// age = 30; -> 사용 불가
// weight = 7-; -> 사용 불가
name = "Park";
height =175;
id = 1000;
}
static void Main(string[] args)
{
Student s = new Student();
s.Set();
int age = s.GetAge();
int id = s.GetId();
Console.WriteLine("학생 이름: {0}", s.name);
}
}
s.GetAge() : 상속된 객체에서 부모 객체의 public 메서드 호출s.GetId() : 상속된 객체 자신의 메서드 호출public class Car
{
public Car() { }
public Car(int wheel) { this.wheel = wheel; }
...
}
public class Sedan: Car
{
Sedan() { }
Sedan(int wheel) : base(wheel) { }
}
Sedan() : base()와 동일 -> 암시적 부모 클래스 생성자 호출Sedan(int wheel) : base(wheel) -> 명시적 부모 클래스 생성자 호출public class Car
{
protected bool gasoline;
protected Car() { gasoline = true; }
protected Car(int wheel)
{
this.wheel = wheel;
gasoline = false;
}
}
public class Sedan: Car
{
private bool gasoline;
Sedan()
{
gasoline = false;
// base.gasoline = false;
// this.gasoline - false;
}
Sedan(int wheel) : base(wheel) { gasoline = true; }
public void SedanMove()
{
if (base.gasoline) ...
if (this.gasoline) ...
}
}
using System;
class A
{
public A() { Console.WriteLine("A"); }
}
class B: A
{
public B() { Console.WriteLine("B"); }
public B(int foo): this()
{
Console.WriteLine("B({0})", foo);
}
}
class DefaultInitializerTest
{
public static void Main()
{
A a1= new A();
B b1 = new B();
B b2 = new B(100);
}
}
public class Point
{
private int x, y;
public Point(): this(0, 0) { }
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
public void Set(int x, int y)
{
this.x = x;
this.y = y;
}
public void ShowPoint()
{
Console.WriteLine("(" + x + ", " + y +")");
}
}
public class ColorPoint: Point
{
private string color;
public ColorPoint()
{
this.color = "Green";
}
public void SetCoor(string color)
{
this.color = color;
}
public void ShowColorPoint()
{
Console.WriteLine(color);
ShowPoint();
}
}
public class ColorPointApp
{
static void Main() string[] args)
{
Point p = new Point();
p.ShowPoint();
ColorPoint cp = new ColorPOint(5, 7, "Blue");
cp.ShowColorPoint();
cp = new ColorPoint();
cp.ShowColorPoint();
}
}
is a Vehicle.is a animal.class Animal
{
}
class Dog: Aniaml
{
}
예시
도서관은 책을 가지고 있다. = Libraryhas abook.
거실은 소파를 가지고 있다. = Living roomhas asofa.
has a radio.class Radio
{
public void TurnOn(bool on)
{
if (on)
Console.WriteLine("Radio On");
else
Console.WriteLine("Radio Off");
}
}
public class Car
{
private Radio music;
public Car()
{
music = new Radio(); // Car has-a Radio
}
public void MusicOn(bool on)
{
music.TurnOn(on); // 자식 객체(Radio)의 기능을 부모 객체(Car)에 위임
}
}
class Airconditioner
{
public void Up() { temperature++; }
public void Down() { temperature--; }
}
public class Car
{
private Airconditioner aircon;
public Car()
{
aircon = new Airconditioner(); // Car has-a Aircon
}
public void TemperatureUp { aircon.Up(); }
public void TemperatureDown() { aircon.Down(); }
}
public class CarHasATest
{
public static Main()
{
// 차를 생성할 때 동시에 라디오와 에어컨 생성
Car c = new Car("Avante");
// 라디오 On
c.MusicOn(true);
// 에어컨 온도 높인다
c.TemperatureUp();
}
}
쉽게 말해서
Car클래스가Radio클래스 객체를 생성해서 사용하는 것을 의미한다.
class Person
{
class Student: Person
{
}
Student student = new Student();
Person person = student;
}
person는 Student 객체를 참조하고 있지만, 타입은 Person이라서 Person에 정의된 멤버만 사용할 수 있다.class Person
{
protected string name;
protected int id;
public Person(string name)
{
this.name = name;
}
}
class Student: Person
{
string grade;
string dept;
public Student(string name) : base(name) { }
public static void Main(string[] args)
{
Person person;
Student student = new Student("Park");
person = student; // 업캐스팅
Console.WriteLine(p.name); // 오류 X
}
}
p.grade = "A" → 컴파일 오류p.dept = "CS" → 컴파일 오류class Person
{
}
class Student: Person
{
}
Student student = new Student();
Person person = student; // 업캐스팅, 자동타입변환
Studnet student = (Student)person; // 다운캐스팅, 강제타입변환
public static void Main(String[] args)
{
Person p = new Student("Park"); // 업캐스팅
Student s = (Student)p; // 다운캐스팅
Console.WriteLine(s.name); // 오류 X
s.grade = "A"; // 오류 X
s.dept = "CS"; // 오류 X
}
override 키워드를 사용한다. (선택적)static, private과 함께 사용할 수 없다.class Shape
{
public string Name()
{
...
}
public virtual void Draw()
{
Console.WriteLine("그림을 그린다.);
}
}
class Circle: Shape
{
public override void Draw()
{
Console.WriteLine("원을 그린다.");
}
}
public class MethodOverridingEx
{
public static void Main(string[] args)
{
Shape shape = new Shape();
Circle circle = new Circle();
Shape a = new Circle(); // 업캐스팅
Shape b = circle; // 업캐스팅
shape.Draw(); // Shape Draw() 실행
circle.Draw(); // Circle Draw() 실행
a.Draw(); // 오버라이딩된 Circle Draw() 실행
b.Draw(); // 오버라이딩된 Circle Draw() 실행
}
}
Draw() 메서드는 virtual로 선언되어 있어서Circle의 Draw()가 실행된다. abstract 키워드를 통해 정의한 메서드를 자식 클래스에서 override하여 재정의한다. (필수적)abstract class Shape
{
public abstract void Draw() { }
}
public class Circle: Shape
{
public override void Draw() { }
}
class AbstractTest
{
static void Main()
{
Shape shape = new Circle();
shape.Draw(); // Circle Draw()
shape = new Square();
shape.Draw(); // Square Draw()
}
}
virtual 키워드와 함께 사용할 수 없다.abstract 키워드를 사용해야 한다.abstract class Ticket
{
public virtual string StartTime() { }
public abstract int Fare(); // 강제성 메서드명만 정의
}
class BusTicket: Ticket
{
public override string StartTime() { }
public override int Fare() {} // 자식 클래스에서 선언
}