在下面的例子中,我们创建了一个名为Human的类。这个类包含属性name(代表人的名字)和friend(代表朋友的名字)。Human类中的每个方法都包含一个指令列表,它同时使用了name和friend属性。
蟒蛇
这段代码是用Python编写的。
class Human(object): def __init__(self, name, friend=None): self.name = name self.friend = friend def say_name(self): print("My name is "+self.name) def say_goodnight(self): if self.friend is None: print("Good night nobody.") else: print("Good night "+self.name) # 创建一个名为Stephen的新Human对象,名字为"Stephen" stephen = Human("Stephen") # 创建一个名为joe的新Human对象,名字为"Joe",并将Stephen作为朋友 joe = Human("Joe", stephen) stephen.say_name() # 显示'我的名字是Stephen' stephen.say_goodnight() # 显示'Good night nobody.' joe.say_name() # 显示'我的名字是Joe' joe.say_goodnight() # 显示'Good night Stephen'。
爪哇
这段代码是用Java编写的。
人文类
class Human { private String name = "unnamed"; // the name of this Human private Human friend = null; // the Human's friend // This method creates a new Human object when given the name and friend public Human(String name, Human friend) { this. name = namethis.}// 当只给定名称时,该方法也创建一个新的Human对象 public Human(String name) { this.name = name; this.friend = null; }。// 当没有同时给定名称和朋友时,该方法会创建一个新的Human对象 public Human() { this.println("我的名字是" + this. name); public void sayGoodnight() { if (friend == null) { System. out. println("Good night nobody."); } else { System.}}
一个与上面的Human类对话的方法
class Main { public static void main(String[] args) { // Create a new Human object stephen with name "Stephen" Human stephen = new Human("Stephen"); // Create a new Human object joe with name "Joe" and stephen as a friend Human joe = new Human("Joe", stephen); stephen.sayName(); // Shows 'My name is Stephen' stephen.sayName(); // 显示"我的名字是Stephen"Stephen.sayGoodnight(); // 显示"晚安,没有人"joe.sayName(); // 显示"我的名字是Joe"joe.sayGoodnight(); // 显示"晚安,Stephen"}。}