Csharp/C Sharp/Class Interface/Class Inheritance — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 11:39, 26 мая 2010
Содержание
- 1 A base class reference can refer to a derived class object
- 2 a multilevel hierarchy
- 3 A multilevel hierarchy 1
- 4 An example of inheritance-related name hiding
- 5 A simple class hierarchy
- 6 Build a derived class of Vehicle for trucks
- 7 Call a hidden method
- 8 Class Hierarchy test
- 9 Class Hierarchy with two children class
- 10 Demonstrate when constructors are called
- 11 Four layers of class hierarchy
- 12 illustrates inheritance
- 13 Illustrates versioning
- 14 Inheritance 3
- 15 Pass a derived class reference to a base class reference
- 16 Private field and public Property in inheritance
- 17 Using base to overcome name hiding
A base class reference can refer to a derived class object
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// A base class reference can refer to a derived class object.
using System;
class X {
public int a;
public X(int i) {
a = i;
}
}
class Y : X {
public int b;
public Y(int i, int j) : base(j) {
b = i;
}
}
public class BaseRef {
public static void Main() {
X x = new X(10);
X x2;
Y y = new Y(5, 6);
x2 = x; // OK, both of same type
Console.WriteLine("x2.a: " + x2.a);
x2 = y; // still Ok because Y is derived from X
Console.WriteLine("x2.a: " + x2.a);
// X references know only about X members
x2.a = 19; // OK
// x2.b = 27; // Error, X doesn"t have a b member
}
}
a multilevel hierarchy
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
/* In a multilevel hierarchy, the
first override of a virtual method
that is found while moving up the
heirarchy is the one executed. */
using System;
class Base {
// Create virtual method in the base class.
public virtual void who() {
Console.WriteLine("who() in Base");
}
}
class Derived1 : Base {
// Override who() in a derived class.
public override void who() {
Console.WriteLine("who() in Derived1");
}
}
class Derived2 : Derived1 {
// This class also does not override who().
}
class Derived3 : Derived2 {
// This class does not override who().
}
public class NoOverrideDemo2 {
public static void Main() {
Derived3 dOb = new Derived3();
Base baseRef; // a base-class reference
baseRef = dOb;
baseRef.who(); // calls Derived1"s who()
}
}
A multilevel hierarchy 1
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// A multilevel hierarchy.
using System;
class TwoDShape {
double pri_width; // private
double pri_height; // private
// Default constructor.
public TwoDShape() {
width = height = 0.0;
}
// Constructor for TwoDShape.
public TwoDShape(double w, double h) {
width = w;
height = h;
}
// Construct object with equal width and height.
public TwoDShape(double x) {
width = height = x;
}
// Properties for width and height.
public double width {
get { return pri_width; }
set { pri_width = value; }
}
public double height {
get { return pri_height; }
set { pri_height = value; }
}
public void showDim() {
Console.WriteLine("Width and height are " +
width + " and " + height);
}
}
// A derived class of TwoDShape for triangles.
class Triangle : TwoDShape {
string style; // private
/* A default constructor. This invokes the default
constructor of TwoDShape. */
public Triangle() {
style = "null";
}
// Constructor
public Triangle(string s, double w, double h) : base(w, h) {
style = s;
}
// Construct an isosceles triangle.
public Triangle(double x) : base(x) {
style = "isosceles";
}
// Return area of triangle.
public double area() {
return width * height / 2;
}
// Display a triangle"s style.
public void showStyle() {
Console.WriteLine("Triangle is " + style);
}
}
// Extend Triangle.
class ColorTriangle : Triangle {
string color;
public ColorTriangle(string c, string s,
double w, double h) : base(s, w, h) {
color = c;
}
// Display the color.
public void showColor() {
Console.WriteLine("Color is " + color);
}
}
public class Shapes6 {
public static void Main() {
ColorTriangle t1 =
new ColorTriangle("Blue", "right", 8.0, 12.0);
ColorTriangle t2 =
new ColorTriangle("Red", "isosceles", 2.0, 2.0);
Console.WriteLine("Info for t1: ");
t1.showStyle();
t1.showDim();
t1.showColor();
Console.WriteLine("Area is " + t1.area());
Console.WriteLine();
Console.WriteLine("Info for t2: ");
t2.showStyle();
t2.showDim();
t2.showColor();
Console.WriteLine("Area is " + t2.area());
}
}
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// An example of inheritance-related name hiding.
using System;
class A {
public int i = 0;
}
// Create a derived class.
class B : A {
new int i; // this i hides the i in A
public B(int b) {
i = b; // i in B
}
public void show() {
Console.WriteLine("i in derived class: " + i);
}
}
public class NameHiding {
public static void Main() {
B ob = new B(2);
ob.show();
}
}
A simple class hierarchy
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// A simple class hierarchy.
using System;
public class Shapes {
public static void Main() {
Triangle t1 = new Triangle();
Triangle t2 = new Triangle();
t1.width = 4.0;
t1.height = 4.0;
t1.style = "isosceles";
t2.width = 8.0;
t2.height = 12.0;
t2.style = "right";
Console.WriteLine("Info for t1: ");
t1.showStyle();
t1.showDim();
Console.WriteLine("Area is " + t1.area());
Console.WriteLine();
Console.WriteLine("Info for t2: ");
t2.showStyle();
t2.showDim();
Console.WriteLine("Area is " + t2.area());
}
}
// A class for two-dimensional objects.
public class TwoDShape {
public double width;
public double height;
public void showDim() {
Console.WriteLine("Width and height are " +
width + " and " + height);
}
}
// Triangle is derived from TwoDShape.
public class Triangle : TwoDShape {
public string style; // style of triangle
// Return area of triangle.
public double area() {
return width * height / 2;
}
// Display a triangle"s style.
public void showStyle() {
Console.WriteLine("Triangle is " + style);
}
}
Build a derived class of Vehicle for trucks
/*
C# A Beginner"s Guide
By Schildt
Publisher: Osborne McGraw-Hill
ISBN: 0072133295
*/
/*
Project 8-1
Build a derived class of Vehicle for trucks.
*/
using System;
class Vehicle {
int pri_passengers; // number of passengers
int pri_fuelcap; // fuel capacity in gallons
int pri_mpg; // fuel consumption in miles per gallon
// This is a constructor for Vehicle.
public Vehicle(int p, int f, int m) {
passengers = p;
fuelcap = f;
mpg = m;
}
// Return the range.
public int range() {
return mpg * fuelcap;
}
// Compute fuel needed for a given distance.
public double fuelneeded(int miles) {
return (double) miles / mpg;
}
// Properties
public int passengers {
get { return pri_passengers; }
set { pri_passengers = value; }
}
public int fuelcap {
get { return pri_fuelcap; }
set { pri_fuelcap = value; }
}
public int mpg {
get { return pri_mpg; }
set { pri_mpg = value; }
}
}
// Use Vehicle to create a Truck specialization.
class Truck : Vehicle {
int pri_cargocap; // cargo capacity in pounds
// This is a constructor for Truck.
public Truck(int p, int f, int m, int c) : base(p, f, m)
{
cargocap = c;
}
// Property for cargocap.
public int cargocap {
get { return pri_cargocap; }
set { pri_cargocap = value; }
}
}
public class TruckDemo {
public static void Main() {
// construct some trucks
Truck semi = new Truck(2, 200, 7, 44000);
Truck pickup = new Truck(3, 28, 15, 2000);
double gallons;
int dist = 252;
gallons = semi.fuelneeded(dist);
Console.WriteLine("Semi can carry " + semi.cargocap +
" pounds.");
Console.WriteLine("To go " + dist + " miles semi needs " +
gallons + " gallons of fuel.\n");
gallons = pickup.fuelneeded(dist);
Console.WriteLine("Pickup can carry " + pickup.cargocap +
" pounds.");
Console.WriteLine("To go " + dist + " miles pickup needs " +
gallons + " gallons of fuel.");
}
}
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Call a hidden method.
using System;
class A {
public int i = 0;
// show() in A
public void show() {
Console.WriteLine("i in base class: " + i);
}
}
// Create a derived class.
class B : A {
new int i; // this i hides the i in A
public B(int a, int b) {
base.i = a; // this uncovers the i in A
i = b; // i in B
}
// This hides show() in A. Notice the use of new.
new public void show() {
base.show(); // this calls show() in A
// this displays the i in B
Console.WriteLine("i in derived class: " + i);
}
}
public class UncoverName123 {
public static void Main() {
B ob = new B(1, 2);
ob.show();
}
}
Class Hierarchy test
/*
Learning C#
by Jesse Liberty
Publisher: O"Reilly
ISBN: 0596003765
*/
using System;
class Window
{
// constructor takes two integers to
// fix location on the console
public Window(int top, int left)
{
this.top = top;
this.left = left;
}
// simulates drawing the window
public void DrawWindow()
{
Console.WriteLine("Drawing Window at {0}, {1}",
top, left);
}
// these members are private and thus invisible
// to derived class methods; we"ll examine this
// later in the chapter
private int top;
private int left;
}
// ListBox derives from Window
class ListBox : Window
{
// constructor adds a parameter
public ListBox(
int top,
int left,
string theContents):
base(top, left) // call base constructor
{
mListBoxContents = theContents;
}
// a new version (note keyword) because in the
// derived method we change the behavior
public new void DrawWindow()
{
base.DrawWindow(); // invoke the base method
Console.WriteLine ("Writing string to the listbox: {0}",
mListBoxContents);
}
private string mListBoxContents; // new member variable
}
public class HierarchyTester
{
public static void Main()
{
// create a base instance
Window w = new Window(5,10);
w.DrawWindow();
// create a derived instance
ListBox lb = new ListBox(20,30,"Hello world");
lb.DrawWindow();
}
}
Class Hierarchy with two children class
/*
Learning C#
by Jesse Liberty
Publisher: O"Reilly
ISBN: 0596003765
*/
using System;
class Window
{
// constructor takes two integers to
// fix location on the console
public Window(int top, int left)
{
this.top = top;
this.left = left;
}
// simulates drawing the window
public virtual void DrawWindow()
{
Console.WriteLine("Window: drawing Window at {0}, {1}",
top, left);
}
// these members are protected and thus visible
// to derived class methods. We"ll examine this
// later in the chapter
protected int top;
protected int left;
}
// ListBox derives from Window
class ListBox : Window
{
// constructor adds a parameter
public ListBox(
int top,
int left,
string contents):
base(top, left) // call base constructor
{
listBoxContents = contents;
}
// an overridden version (note keyword) because in the
// derived method we change the behavior
public override void DrawWindow()
{
base.DrawWindow(); // invoke the base method
Console.WriteLine ("Writing string to the listbox: {0}",
listBoxContents);
}
private string listBoxContents; // new member variable
}
class Button : Window
{
public Button(
int top,
int left):
base(top, left)
{
}
// an overridden version (note keyword) because in the
// derived method we change the behavior
public override void DrawWindow()
{
Console.WriteLine("Drawing a button at {0}, {1}\n",
top, left);
}
}
public class TesterClassArray1
{
static void Main()
{
Window win = new Window(1,2);
ListBox lb = new ListBox(3,4,"Stand alone list box");
Button b = new Button(5,6);
win.DrawWindow();
lb.DrawWindow();
b.DrawWindow();
Window[] winArray = new Window[3];
winArray[0] = new Window(1,2);
winArray[1] = new ListBox(3,4,"List box in array");
winArray[2] = new Button(5,6);
for (int i = 0;i < 3; i++)
{
winArray[i].DrawWindow();
}
}
}
Demonstrate when constructors are called
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Demonstrate when constructors are called.
using System;
// Create a base class.
class A {
public A() {
Console.WriteLine("Constructing A.");
}
}
// Create a class derived from A.
class B : A {
public B() {
Console.WriteLine("Constructing B.");
}
}
// Create a class derived from B.
class C : B {
public C() {
Console.WriteLine("Constructing C.");
}
}
public class OrderOfConstruction {
public static void Main() {
C c = new C();
}
}
Four layers of class hierarchy
/*
* C# Programmers Pocket Consultant
* Author: Gregory S. MacBeth
* Email: gmacbeth@comporium.net
* Create Date: June 27, 2003
* Last Modified Date:
*/
using System;
namespace Client.Chapter_5___Building_Your_Own_Classes
{
public class MyMainClass3
{
static void Main(string[] args)
{
//The function called is based
//upon the type called by new.
A MyA = new D();
B MyB = new C();
MyA.Display(); //Calls D Display
MyB.Display(); //Calls C Display
// followed by B"s Display //via the base keyword
}
}
class A
{
public virtual void Display()
{
Console.WriteLine("Class A"s Display Method");
}
}
class B: A
{
public override void Display()
{
Console.WriteLine("Class B"s Display Method");
}
}
class C: B
{
public override void Display()
{
Console.WriteLine("Class C"s Display Method");
base.Display();
}
}
class D: C
{
public override void Display()
{
Console.WriteLine("Class D"s Display Method");
}
}
}
illustrates inheritance
/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
Example7_1.cs illustrates inheritance
*/
using System;
// declare the MotorVehicle class (the base class)
class MotorVehicle
{
// declare the fields
public string make;
public string model;
// define a constructor
public MotorVehicle(string make, string model)
{
this.make = make;
this.model = model;
}
// define a method
public void Start()
{
Console.WriteLine(model + " started");
}
}
// declare the Car class (derived from the MotorVehicle base class)
class Car : MotorVehicle
{
// declare an additional field
public bool convertible;
// define a constructor
public Car(string make, string model, bool convertible) :
base(make, model) // calls the base class constructor
{
this.convertible = convertible;
}
}
// declare the Motorcycle class (derived from the MotorVehicle base class)
class Motorcycle : MotorVehicle
{
// declare an additional field
public bool sidecar;
// define a constructor
public Motorcycle(string make, string model, bool sidecar) :
base(make, model) // calls the base class constructor
{
this.sidecar = sidecar;
}
// define an additional method
public void PullWheelie()
{
Console.WriteLine(model + " pulling a wheelie!");
}
}
public class Example7_1
{
public static void Main()
{
// declare a Car object, display the object"s fields, and call the
// Start() method
Car myCar = new Car("Toyota", "MR2", true);
Console.WriteLine("myCar.make = " + myCar.make);
Console.WriteLine("myCar.model = " + myCar.model);
Console.WriteLine("myCar.convertible = " + myCar.convertible);
myCar.Start();
// declare a Motorcycle object, display the object"s fields, and call the
// Start() method
Motorcycle myMotorcycle = new Motorcycle("Harley-Davidson", "V-Rod", false);
Console.WriteLine("myMotorcycle.make = " + myMotorcycle.make);
Console.WriteLine("myMotorcycle.model = " + myMotorcycle.model);
Console.WriteLine("myMotorcycle.sidecar = " + myMotorcycle.sidecar);
myMotorcycle.Start();
myMotorcycle.PullWheelie();
}
}
Illustrates versioning
/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
Example7_5.cs illustrates versioning
*/
using System;
// declare the MotorVehicle class
class MotorVehicle
{
// declare the fields
public string make;
public string model;
// define a constructor
public MotorVehicle(string make, string model)
{
this.make = make;
this.model = model;
}
// define the Accelerate() method
public virtual void Accelerate()
{
Console.WriteLine("In MotorVehicle Accelerate() method");
Console.WriteLine(model + " accelerating");
}
}
// declare the Car class (derived from MotorVehicle)
class Car : MotorVehicle
{
// define a constructor
public Car(string make, string model) :
base(make, model)
{
// do nothing
}
// define the Accelerate() method (uses the new keyword to
// tell the compiler a new method is to be defined)
public new void Accelerate()
{
Console.WriteLine("In Car Accelerate() method");
Console.WriteLine(model + " accelerating");
}
}
public class Example7_5
{
public static void Main()
{
// create a Car object
Console.WriteLine("Creating a Car object");
Car myCar = new Car("Toyota", "MR2");
// call the Car object"s Accelerate() method
Console.WriteLine("Calling myCar.Accelerate()");
myCar.Accelerate();
}
}
Inheritance 3
/*
* C# Programmers Pocket Consultant
* Author: Gregory S. MacBeth
* Email: gmacbeth@comporium.net
* Create Date: June 27, 2003
* Last Modified Date:
*/
using System;
namespace Client.Chapter_5___Building_Your_Own_Classes
{
public class InheritanceChapter_5___Building_Your_Own_Classes
{
static void Main(string[] args)
{
B MyB = new D();
D MyD = new D();
//Both result in in D"s instance of Display being //called
MyB.Display();
MyD.Display();
}
}
public class B
{
public virtual void Display()
{
Console.WriteLine("Class B"s Display Method");
}
}
public class C: B
{
public override void Display()
{
Console.WriteLine("Class C"s Display Method");
}
}
public class ContainedClass
{
int MyInt = 0;
}
public class D: C
{
public ContainedClass MyClass = new ContainedClass();
public override void Display()
{
Console.WriteLine("Class D"s Display Method");
}
}
}
Pass a derived class reference to a base class reference
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Pass a derived class reference to a base class reference.
using System;
class TwoDShape {
double pri_width; // private
double pri_height; // private
// Default constructor.
public TwoDShape() {
width = height = 0.0;
}
// Constructor for TwoDShape.
public TwoDShape(double w, double h) {
width = w;
height = h;
}
// Construct object with equal width and height.
public TwoDShape(double x) {
width = height = x;
}
// Construct object from an object.
public TwoDShape(TwoDShape ob) {
width = ob.width;
height = ob.height;
}
// Properties for width and height.
public double width {
get { return pri_width; }
set { pri_width = value; }
}
public double height {
get { return pri_height; }
set { pri_height = value; }
}
public void showDim() {
Console.WriteLine("Width and height are " +
width + " and " + height);
}
}
// A derived class of TwoDShape for triangles.
class Triangle : TwoDShape {
string style; // private
// A default constructor.
public Triangle() {
style = "null";
}
// Constructor for Triangle.
public Triangle(string s, double w, double h) : base(w, h) {
style = s;
}
// Construct an isosceles triangle.
public Triangle(double x) : base(x) {
style = "isosceles";
}
// Construct an object from an object.
public Triangle(Triangle ob) : base(ob) {
style = ob.style;
}
// Return area of triangle.
public double area() {
return width * height / 2;
}
// Display a triangle"s style.
public void showStyle() {
Console.WriteLine("Triangle is " + style);
}
}
public class Shapes7 {
public static void Main() {
Triangle t1 = new Triangle("right", 8.0, 12.0);
// make a copy of t1
Triangle t2 = new Triangle(t1);
Console.WriteLine("Info for t1: ");
t1.showStyle();
t1.showDim();
Console.WriteLine("Area is " + t1.area());
Console.WriteLine();
Console.WriteLine("Info for t2: ");
t2.showStyle();
t2.showDim();
Console.WriteLine("Area is " + t2.area());
}
}
Private field and public Property in inheritance
/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
namespace nsInherit
{
using System;
public class clsMainInherit
{
static public void Main ()
{
clsDerived derived = new clsDerived();
derived.Property = 42;
derived.ShowField();
}
}
//
// Define a base class with a private field and a public Property
class clsBase
{
private int m_Field;
public int Property
{
get {return (m_Field);}
set {m_Field = value;}
}
public void ShowField ()
{
Console.WriteLine ("The value of m_Field is " + m_Field);
}
}
//
// Define a derived class that inherits from the clsBase
class clsDerived : clsBase
{
// For now, the derived class needs no members
}
}
Using base to overcome name hiding
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Using base to overcome name hiding.
using System;
class A {
public int i = 0;
}
// Create a derived class.
class B : A {
new int i; // this i hides the i in A
public B(int a, int b) {
base.i = a; // this uncovers the i in A
i = b; // i in B
}
public void show() {
// this displays the i in A.
Console.WriteLine("i in base class: " + base.i);
// this displays the i in B
Console.WriteLine("i in derived class: " + i);
}
}
public class UncoverName1231 {
public static void Main() {
B ob = new B(1, 2);
ob.show();
}
}