声明类Person,包含2个成员变量:name、age。定义函数sayHello(),调用时输出:我叫***,今年***岁了。声明类Chinese继承Person。
  P66d8Dsrd4Sr 2023年11月02日 25 0


/*
*第7题:
* 声明类Person,包含2个成员变量:name、age。定义函数sayHello(),调用时输出:我叫***,今年***岁了。声明类Chinese继承Person
*/
public class Person {
private String name;//姓名
String gender;//性别
public int age;//年龄

/*
* 类成员的访问控制修饰符
* 1,private只在同一类中可以使用
* 2,无修饰符 在同一类,同一包下的类可以使用
* 3,protected 在同一类,同一包,其子类可以使用
* 4,public 在任何地方都可以使用
*/
/*
* 1,将属性私有化
* 2,设置get/set方法
* 3,设置必要的读取限制
*/



public String getName() {
return name;
}


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


public String getGender() {
return gender;
}


public void setGender(String gender) {
if(gender.equals("男")||gender.equals("女"))
this.gender = gender;
else
System.out.println("***性别不合法***");
}


public int getAge() {
return age;
}


public void setAge(int age) {
if(age<0||age>150){
System.out.println("***年龄不合法***");
return;
}
this.age = age;
}


//构造方法
public Person(){
this.name = "无名氏";
this.gender = "男";
this.age = 18;
}

public Person(String name,String gender,int age){
this.name = name;
this.gender = gender;
this.age = age;
}

//方法自我介绍
public void say(){
System.out.println("自我介绍一下\r\n姓名:"+this.name+"\r\n性别:"
+this.gender+"\r\n年龄:"+this.age+"岁");

}


}





2.

package com.itheima;


public class PersonTest {




public static void main(String[] args) {
Person hanbing=new Person();
/*hanbing.name="韩冰";
hanbing.age=200;
hanbing.gender="中性";*/

hanbing.setName("韩冰");
hanbing.setAge(200);
hanbing.setGender("中性");
//hanbing.gender="男";
//hanbing.age=25;
//hanbing.age =25;
hanbing.say();


}


}



3.

package com.itheima2;
import com.itheima.Person;
public class PersonTest {



public static void main(String[] args) {
Person hanbing=new Person();
hanbing.say();
//hanbing.age =25;


}


}


【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

P66d8Dsrd4Sr
最新推荐 更多