boy and girl
boy
package com.atguigu.exer2;
public class Boy
{
private String name;//姓名
private int age;//年龄 //属性
public Boy() { //构造器
}
public Boy(String name){
this.name = name;
}
public Boy(String name, int age){
this.name = name;
this.age = age;
}
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 void marry(Girl girl) {
System.out.println("我想娶"+girl.getName());
}
public void shout() {
if(this.age >= 22) {
System.out.println("你可以去合法登记结婚了");
}else {
System.out.println("先多谈谈恋爱吧");
}
}
}
girl
package com.atguigu.exer2;
public class Girl
{
private String name;
private int age; //属性
public Girl(String name, int age) { //构造器
this.name = name;
this.age = age;
}
public Girl() {
}
public String getName() { //方法
return name;
}
public void setName(String name) {
this.name = name;
}
public void marry(Boy boy) {
System.out.println("我想嫁给" + boy.getName());
boy.marry(this);
}
/**
*
* @Description 比较两个对象的大小
* author LeungKiChen
* @date 2021年6月20日下午10:49:19
* @param girl
* @return 正数 当前对象大 负数 当前对象小 0 二者相同(当前对象 形参对象)
*/
public int compare(Girl girl) {
/* if(this.age > girl.age) {
return 1;
}else if(this.age < girl.age) {
return -1;
}else {
return 0;
} */
return this.age - girl.age;
}
}
test
package com.atguigu.exer2;
public class BoyGirlTest
{
public static void main(String [] arge) {
Boy boy = new Boy("罗密欧", 21);
boy.shout();
Girl girl = new Girl("朱丽叶",18);
girl.marry(boy);
Girl girl1 = new Girl("祝英台" , 19);
int compare = girl.compare(girl1);
if(compare > 0) {
System.out.println(girl.getName()+"大");
}else if( compare < 0) {
System.out.println(girl1.getName()+"大");
}else {
System.out.println("二者年龄相等");
}
}
}
该博客展示了Java编程中面向对象的概念,包括Boy和Girl类的定义,包含姓名和年龄属性以及构造器、getter/setter方法。Boy类具有求婚和判断是否可以结婚的方法,Girl类具有比较年龄的方法。在测试类中,创建了Boy和Girl对象并演示了他们的交互,如求婚和比较年龄的操作。
464

被折叠的 条评论
为什么被折叠?



