C++
Person中age为私有的,通过Persron::getAge()可以获取age的值。
#include <iostream>
using namespace std;
class Person
{
public:
Person(int a) {
this->age = a;
}
int getAge() {
return age;
}
private:
int age;
};
class Man : public Person
{
public:
Man(string name, int add, int age):Person(age) {
this->name = name;
this->add = add;
}
int getAge() {
return add + Person::getAge();
}
string getName() {
return name;
}
private:
string name;
int add;
};
int main()
{
Man m1("Test", 12, 15);
cout << m1.getName() << " " << m1.getAge() << endl;
return 0;
}
JAVA:使用super调用父类的读域函数getAge()
Person.java
package test;
public class Person {
public Person(int age) {
this.aAge = age;
}
public int getAge() {
return aAge;
}
public void setAge(int age) {
aAge = age;
}
private int aAge;
}
Male.java
package test;
public class Male extends Person
{
public Male(int age, int add) {
super(age);
this.add = add;
}
public int getAge() {
return this.add + super.getAge();
}
private int add;
public static void main(String[] args) {
System.out.println(new Male(12, 15).getAge());
}
}
~