gpt4 book ai didi

java - 在继承中使用私有(private)变量

转载 作者:行者123 更新时间:2023-11-30 10:31:05 24 4
gpt4 key购买 nike

<分区>

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 类。我应该只使用私有(private)变量。

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() 中返回本科生姓名和地址,如果我使用私有(private)变量是否可行。

预期输出:

kim hno 123

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com