栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java基础:面向对象编程23-this课后练习boy&girl

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java基础:面向对象编程23-this课后练习boy&girl

package com.atguigu.exer4;

public class Girl {
	
	 private String name;
	 private int age;
	 
	 
	 
	 public void marry(Boy boy){
		 if(boy.getAge()<18){
			 System.out.println(this.name+":"+boy.getName()+"你个小屁孩一边玩去");
		 }else if(boy.getAge()<25){
			 System.out.println(this.name+":"+boy.getName()+"咱们先恋爱吧");
		 }else{
			 System.out.println(this.name+":"+boy.getName()+"咱们结婚爱吧");
			 boy.marry(this);  //this指代上边的girl
		 }
	 }
	 
	 public void compare(Girl girl){
		 if(this.getAge()> girl.getAge()){
			 System.out.println(girl.getName()+"比"+this.getName()+"漂亮");
		 }else if(this.getAge()< girl.getAge()){
			 System.out.println(this.getName()+"比"+girl.getName()+"漂亮");
		 }else{
			 System.out.println(this.getName()+"和"+girl.getName()+"都漂亮");
		 }
	 }
	 
	public Girl(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;
	}
	
	
	
}
package com.atguigu.exer4;

public class Boy {
	 private String name;
	 private int age;
	
	 public Boy(String name, int age) {		
		this.name = name;
		this.age = age;
	}
	 
	 
	 public void marry(Girl girl){
		 this.shout();     //由于 是  boy.marry所有这里的this指代的boy
		 System.out.println(this.name+":"+girl.getName()+"我要爱你一万年");
	 }
	 
	 public void shout(){
		 System.out.println(this.name+":我要结婚了");
	 }
	 
	 
	 
	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;
	}
	 
		
	
}
package com.atguigu.exer4;

public class Test {
	public static void main(String[] args) {
		Boy boy = new Boy("小龙哥", 30);
		Girl girl = new Girl("苍老师", 18);
		
		girl.marry(boy);  //girl调用的marry,因此marry方法中的this指代的是girl对象
		
	System.out.println("--------------------------");
	
		Girl girl2 = new Girl("志林姐", 20);
		girl.compare(girl2);
	}

}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/446043.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号