当前位置: 面试刷题>> getter与setter (经典算法题500道)


### 题目描述补充 在面向对象编程中,getter和setter方法是非常重要的概念。它们分别用于获取(get)和设置(set)对象的私有属性,从而实现对对象属性的封装和保护。封装是面向对象编程的三大特性(封装、继承、多态)之一,它隐藏了对象的内部细节,仅通过公共接口(如getter和setter方法)与外界交互。 现在,请实现一个简单的类`Person`,该类包含私有属性`name`和`age`,并为这两个属性分别编写getter和setter方法。此外,为了展示面向对象的多态性(虽然在这个特定问题中不直接体现多态,但我们可以考虑增加一个方法如`describe`来体现对象的行为),可以添加一个`describe`方法来输出人的基本信息。 ### 示例代码 #### PHP ```php class Person { private $name; private $age; // Setter for name public function setName($name) { $this->name = $name; } // Getter for name public function getName() { return $this->name; } // Setter for age public function setAge($age) { $this->age = $age; } // Getter for age public function getAge() { return $this->age; } // Describe method to demonstrate behavior public function describe() { echo "Name: " . $this->name . ", Age: " . $this->age . "\n"; } } // Example usage $person = new Person(); $person->setName("John Doe"); $person->setAge(30); $person->describe(); // Output: Name: John Doe, Age: 30 ``` #### Python ```python class Person: def __init__(self): self.__name = None self.__age = None # Setter for name def set_name(self, name): self.__name = name # Getter for name def get_name(self): return self.__name # Setter for age def set_age(self, age): self.__age = age # Getter for age def get_age(self): return self.__age # Describe method to demonstrate behavior def describe(self): print(f"Name: {self.__name}, Age: {self.__age}") # Example usage person = Person() person.set_name("John Doe") person.set_age(30) person.describe() # Output: Name: John Doe, Age: 30 ``` #### JavaScript ```javascript class Person { constructor() { this._name = null; this._age = null; } // Setter for name set name(name) { this._name = name; } // Getter for name get name() { return this._name; } // Setter for age set age(age) { this._age = age; } // Getter for age get age() { return this._age; } // Describe method to demonstrate behavior describe() { console.log(`Name: ${this._name}, Age: ${this._age}`); } } // Example usage let person = new Person(); person.name = "John Doe"; person.age = 30; person.describe(); // Output: Name: John Doe, Age: 30 ``` ### 码小课网站分享 码小课网站中提供了更多关于面向对象编程、getter与setter方法、以及JavaScript、PHP、Python等编程语言的深入内容和学习资源,欢迎大家访问学习,不断提升自己的编程技能。
推荐面试题