-
对象是一组属性和方法(事件)的组合
class program { void main(string[] args) { //没有类的话 string userName = "Tim";//定义一个字符串变量 int userAge = 18;//定义一个32位无符号整数变量 Console.WriteLine("Name:{0},Age{1}",userName,userAge);//打印用户信息 userName = "Tom";//修改用户信息 userAge = 20; Console.WriteLine("Name:{0},Age{1}",userName,userAge);//打印用户信息 //上面的代码做了两次相同的工作,除了变量值不同 //基于面向对象中的"封装"思想,我们将"userName","userAge"和"输出语句"整合到一起,称为class //封装后的类,只是一个模板,需要实例化才能称为一个可操作的对象,就像一张表,规定了列名之后需要至少一条实际数据才能体现它的内容 //类的实例化,一般同时为它的一些属性赋值 User user1 = new User("Tim",20); //要操作对象内部的属性方法,用类名+"."+属性/方法 user1.ShowInfo(); //对象的属性可以随时修改 user1.name = "Tom"; } }
-
类的作用就是存储和执行一类常用的属性或行为
public class User { public string name="";//属性 public int age = 0;//属性 public User(string n,int a)//构造方法,与方法类似,实例化的时候自动调用 { this.name = n; this.age = a; } public void ShowInfo()//方法 { Console.WriteLine("Name:{0},Age{1}",name,age); } }
-
面向对象的三大特性(封装/继承/多态)
//封装就是类的声明; //继承就是用已有的类作为模板,直接拥有父类有的资源 public class MyUser:User{} MyUser myUser1 = new MyUser("Tim",20); myUser.ShowInfo(); //多态在模板的基础上做一些定制化的修改 public class VipUser:User { public int Money = 99999999999999999999; public void ShowInfo() { Console.WriteLine("Name:{0},Age{1},Money:{2}",name,age,money); } }
-
对象能无限嵌套
public class Cat { string name="cat"; string voice = "miao"; void Speak() { Console.WriteLine(voice+"!"); } } public class Human{} public class Animal { Cat cat = new Cat(); Human human = new Human(); //... } public class Plant{} public class Germ{} public cliass Creature { Animal animal = new animal(); Plant plant = new plant(); Germ germ = new germ(); } /*-生物 --动物 ---猫 ----名称 ----声音 ----发出叫声() ---人类 ---... --植物 --微生物
-
面向对象语言的灵魂在于
(C#/Java/Python).
Creature creature = new Creature(); creature.animal.cat.Speak(); //miao!
暂无评论