在inhertence中使用私有变量

时间:2017-04-11 21:52:55

标签: java inheritance

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());
}

}

我正在尝试扩展Member class.i应该只使用私有变量。

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());
}
}

我继承了会员班和本科班 我想在toString()中返回本科名称和地址,如果我使用私有变量,我可以这样做。

预期产量:

kim hno 123

1 个答案:

答案 0 :(得分:1)

在您的代码中,您无法访问nameaddress,因为它们是private变量,您可以使用getter方法是public,因此您可以在任何类(即,不仅仅是子类)中访问它们,如下面的toString()方法所示:

public String toString() {
   return getAddress() + getName();
}

还有一点值得注意的是,因为Undergraduate IS-A Member(继承),您可以调用getAddress()getName()而无需创建对象Member类,即在非子类(无继承)中,您需要Member类的对象来调用public(实例)方法。