继承和Java差不多,不过重写方法有些差别。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main( string[] args)
{
Foo f = new Foo(1);
Bar b = new Bar(2, "yyyy");
f.f1();
f.f2();
f.ToString();
b.f1();
b.f2();
b.f3();
b.ToString();
Console.ReadLine();
}
}
class Foo
{
public int x;
public Foo( int x)
{
Console.WriteLine( "Foo构造方法被调用了");
this.x = x;
}
public void f1()
{
Console.WriteLine( "f1 come from foo");
}
public void f2()
{
Console.WriteLine( "f2 come from foo");
}
};
class Bar : Foo
{
public Bar( int x, string y)
: base(x)
{
Console.WriteLine( "Bar构造方法被调用了");
Console.WriteLine(y);
}
new public void f1()
{
Console.WriteLine( "f1 come from Bar");
}
public void f3()
{
Console.WriteLine( "f3 come from Bar");
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main( string[] args)
{
Foo f = new Foo(1);
Bar b = new Bar(2, "yyyy");
f.f1();
f.f2();
f.ToString();
b.f1();
b.f2();
b.f3();
b.ToString();
Console.ReadLine();
}
}
class Foo
{
public int x;
public Foo( int x)
{
Console.WriteLine( "Foo构造方法被调用了");
this.x = x;
}
public void f1()
{
Console.WriteLine( "f1 come from foo");
}
public void f2()
{
Console.WriteLine( "f2 come from foo");
}
};
class Bar : Foo
{
public Bar( int x, string y)
: base(x)
{
Console.WriteLine( "Bar构造方法被调用了");
Console.WriteLine(y);
}
new public void f1()
{
Console.WriteLine( "f1 come from Bar");
}
public void f3()
{
Console.WriteLine( "f3 come from Bar");
}
}
}
1、继承符号为冒号:,java用extend
2、子类重写父类方法,前面加上关键字new,java不需要
3、子类调用父类的构造方法用base(),Java中用super
4、子类调用父类的方法用base.xxx(), Java中用super
本文转自 leizhimin 51CTO博客,原文链接:http://blog.51cto.com/lavasoft/194370,如需转载请自行联系原作者