在继承中使用私有变量[重复]
Posted
技术标签:
【中文标题】在继承中使用私有变量[重复]【英文标题】:use private variable in inhertence [duplicate] 【发布时间】:2017-09-07 11:36:35 【问题描述】:public class Member
private String name;
private String address;
public Member(String name,String address)
this.name=name;
this.address=address;
public String getName()
return name;
public void setName(String name)
this.name = name;
public String getAddress()
return address;
public void setAddress(String address)
this.address = address;
public String toString()
return name +","+ " " + address;
public static void main(String[] args)
Member m1=new Member("ravi","h-no :912");
System.out.println(m1.toString());
我正在尝试扩展成员类。我应该只使用私有变量。
import java.util.ArrayList;
public class Undergraduate extends Member
private int numCourses;
private ArrayList<String> courses = new ArrayList<String>();
private ArrayList<Integer> grades = new ArrayList<Integer>();
public Undergraduate(String name, String address)
super(name,address);
public void addCourseGrade(String course,int grade)
courses.add(course);
//String grade1=String.valueOf(grade);
grades.add(grade);
public double getAverageGrade()
double sum=0;
for(int i=0; i < grades.size() ; i++)
sum = sum + grades.get(i);
//calculate average value
double average=0;
average= sum / grades.size();
return average;
public String toString()
return name +address;// i want to return undergraduate name and address here
public static void main(String args[])
Undergraduate undg = new Undergraduate("kimi", "hno 123");
undg.addCourseGrade("CS500", 2);
undg.addCourseGrade("CS560", 1);
System.out.println(undg.toString());
System.out.println(undg.getAverageGrade());
我继承了 Member 类和 Undergraduate 类 如果我使用私有变量,我想在 toString() 中返回本科生姓名和地址。
预期输出:
kim hno 123
【问题讨论】:
【参考方案1】:在您的代码中,您无法访问name
和address
,因为它们是private
变量,您可以使用getter
方法,即public
,所以您可以在任何类(即,不仅是子类)中访问它们,如下所示在您的toString()
方法中:
public String toString()
return getAddress() + getName();
还有一点需要注意的是,因为Undergraduate
IS-A Member
(继承),您可以调用getAddress()
和getName()
而无需为Member
类创建对象,即在非-subclasses(无继承),您需要 Member
类的对象来调用 public
(实例)方法。
【讨论】:
以上是关于在继承中使用私有变量[重复]的主要内容,如果未能解决你的问题,请参考以下文章