案例

package com.Test;

public class Test01 {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle(5,3);
int permeter = rectangle.getPermeter();
System.out.println("周长"+permeter);

int area = rectangle.getArea();
System.out.println("面积"+area);
}
}


class Rectangle{
private int length;
private int width;

/**
* 获取周长的方法
* @return
*/
public int getPermeter(){
return this.length*2 + this.width*2;
}

/**
* 获取面积的方法
* @return
*/
public int getArea(){
return this.length * this.width;
}


public Rectangle(int length, int width) {
this.length = length;
this.width = width;
}
public Rectangle() {


}

@Override
public String toString() {
return "Rectangle{" +
"length=" + length +
", width=" + width +
'}';
}

public int getLength() {
return length;
}

public void setLength(int length) {
this.length = length;
}

public int getWidth() {
return width;
}

public void setWidth(int width) {
this.width = width;
}
}



2.封装一个学生类,有姓名,年龄,性别,英语成绩,数学成绩,语文成绩,封装方法,求总分,平均分,以及打印学生的信息
public class StudentTest {
public static void main(String[] args) {
Student student = new Student("张三",17,"男",97,98,99);
System.out.println(student.getName()+"的平均分="+student.avg());
System.out.println(student.getName()+"的总分="+student.sum());

System.out.println(student.toString());

}
}

class Student{
private String name;
private int age;
private String sex;
private double score1;
private double score2;
private double score3;

public double sum(){
return this.score1 + this.score2 + this.score3;
}

public double avg(){
return (this.score1 + this.score2 + this.score3)/3;
}


public Student() {

}

public Student(String name, int age, String sex, double score1, double score2, double score3) {
this.name = name;
this.age = age;
this.sex = sex;
this.score1 = score1;
this.score2 = score2;
this.score3 = score3;
}

@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
", score1=" + score1 +
", score2=" + score2 +
", score3=" + score3 +
'}';
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String getSex() {
return sex;
}

public void setSex(String sex) {
this.sex = sex;
}

public double getScore1() {
return score1;
}

public void setScore1(double score1) {
this.score1 = score1;
}

public double getScore2() {
return score2;
}

public void setScore2(double score2) {
this.score2 = score2;
}

public double getScore3() {
return score3;
}

public void setScore3(double score3) {
this.score3 = score3;
}
}
posted @ 2022-06-15 15:16  我滴妈老弟  阅读(37)  评论(0编辑  收藏  举报