2010/03/11

C# week7_1

08/03/2010

Inheritance & Polymorphism

 
 

P

________|________

|                |

C1                C2

|                |

C3                C4

 
 

 
 

Auto

|

Collora        

|

Camry

 
 

 
 

Collora c=new Camry();

 
 

class A

{

static public int i=10;

private A()

{

}

}

class B

{

static public int j=20;        

A a=new A(); (error: Because B can't access A.)

A a=new B(); (OK)

a.j; (error: Because j isn't initialized.)

a.i; (OK)

}

 
 

Method overriding

class A

{

vitual public static void xyz()

{

}

}

class B

{

override public static void xyz()

{

}

}

class Program

{

override initialized

----------        

A a=new B();

-------

normal initialized

 
 

a.xyz(); (This method calls B's xyz.)

}        

 
 

Homework

A-non xyz()

|

B

|

C-xyz()

|

D-xyz()

 
 

If you initialize "A a=new D(); a.xyz();", will it work or not?

Answer: It won't work, because class A doesn't have method xyz().

 
 

 
 

Interface

 
 

A                B

|                |

--------|--------

C

In C#, multiple inheritance isn't supported, because it is too complex.

However, if you use interface, you will make programming similar to multiple inheritance.

 
 

interface A

{

public void xyz(); (without body)

public void abc(); (without body)

}

 
 

*The class of Interface should be without body.

 
 

abstract class B

{

public void xyz()

{

}

abstract public void abc(); (without body)

}

 
 

 
 

Interface is better than inheritance.

because: The test of interface is much easier than inheritance.

 
 

interface A

{

public void xyz();

}

 
 

class B:A

{

A a=new A(); (error: no body)

//first complete body

 
 

public override void xyz()

{

}

A a=new B

}

*C# can't make object not complete method such as abstract and interface.

 
 

interface

------

class B:A, c, D

--

inheritance

0 件のコメント:

コメントを投稿

UA-9417263-1