Animal
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| using UnityEngine; using System.Collections;
public class Animal {
public string m_Name; public int m_Age;
public Animal(string name, int age) { this.m_Name = name; this.m_Age = age; }
public Animal() : this("", 0) {
}
public virtual string Info() { return "Name = " + m_Name + ", Age = " + m_Age; } }
|
Dog
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| using UnityEngine; using System.Collections;
public class Dog : Animal {
public int m_DogType;
public Dog(string name, int age, int type) : base(name, age) { this.m_DogType = type; }
public Dog() : this("", 0, 0) {
}
public override string Info () { return base.Info () + ", DogType = " + m_DogType; } }
|
Test
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| using UnityEngine; using System.Collections;
public class Test : MonoBehaviour {
void Start () { Animal a1 = new Animal(); Debug.Log(a1.Info()); Animal a2 = new Animal("a2", 3); Debug.Log(a2.Info());
Dog d1 = new Dog(); Debug.Log(d1.Info()); Dog d2 = new Dog("d2", 2, 1); Debug.Log(d2.Info()); } }
|
如示例,既可以继承自己的构造方法,也可以继承父类的构造方法。