public class FirstDemo {
/**
* 封裝+構造方法小例子
*/
//
private String student;
private String name;
private float math;
private float english;
private float computer;
public String getStudent() {
return student;
}
public void setStudent(String student) {
this.student = student;
public String getName() {
return name;
public void setName(String name) {
this.name = name;
// 屬性
public float getMath() {
return math;
public void setMath(float math) {
this.math = math;
public float getEnglish() {
return english;
public void setEnglish(float english) {
this.english = english;
public float getComputer() {
return computer;
public void setComputer(float computer) {
this.computer = computer;
// 方法
public FirstDemo() {
super();
// 無參構造
public FirstDemo(String s, String n, float m, float e, float c) {
// 含參數構造
this.setStudent(s);
this.setName(n);
this.setMath(m);
this.setEnglish(e);
this.setComputer(c);
public float sum() {
// 求和
return math + english + computer;
public float avg() {
// 平均數
return this.sum() / 3;
public float max() {
// 三科中的最大值
float max = math;// 初始化數學為最高成績
// 三目運算符---如果數學成績大于計算機成績,max=數學成績否則max=computer
// 三目運算符---如果數學成績大于英語成績,max=數學成績否則max=english
// 通過兩次運算獲得三科中最大值
max = max > computer ? max : computer;
max = max > english ? max : english;
return max;
public float min() {
// 三科中的最小值
float min = math;// 初始化數學為最高成績
// 三目運算符---如果數學成績大于計算機成績,min=數學成績否則min=computer
// 三目運算符---如果數學成績大于英語成績,min=數學成績否則min=english
min = min < computer ? min : computer;
min = min < english ? min : english;
return min;
public static void main(String[] args) {
// 具體指派
FirstDemo firstDemo = new FirstDemo("01", "a1", 89, 98, 33);
System.out.print("學生編号:" + firstDemo.getStudent());
System.out.print("\t學生名稱" + firstDemo.getName());
System.out.print("\t數學成績" + firstDemo.getMath());
System.out.print("\t英語成績" + firstDemo.getEnglish());
System.out.print("\t計算機成績" + firstDemo.getComputer());
System.out.print("\t總成績" + firstDemo.sum());
System.out.print("\n平均分" + firstDemo.avg());
System.out.print("\n最大值" + firstDemo.max());
System.out.print("\n最小值" + firstDemo.min());
}