赞
踩
目录
对象属性:姓名、年龄、性别、身高
对象方法:说话、计算加法、年龄长一岁
类属性:学校名称
类方法:学习
封装所有对象属性,编写属性的getter和setter方法;
/创建包,包名可以自拟,在包中创建student类
- package Student;
-
- public class Student {
- //构造器
- public Student(String Name,String Sex,int Age,int height) {
- this.Name=Name;
- this.Sex=Sex;
- this.height=height;
- this.Age=Age;
- }
-
- public String Name; //学生姓名
- public int Age; //学生年龄
- public String Sex; //学生性别
- public int height;//学生身高
-
- public Student() {
-
- }
-
-
- //getter/setter方法
- public int getHeight() {
-
- return height;
- }
-
- public void setHeight(int height) {
-
- this.height = height;
- }
- public String getName() {
-
- return Name;
- }
- public void setName(String name) {
-
- this.Name = name;
- }
-
- //当方法的局部变量和类的成员变量重名的时候,根据就近原则,优先使用局部变量。
- //如果使用访问类的成员变量,使用this.关键字.
- //谁调用的方法谁就是this
- public void setAge(int age) {
-
- this.Age = age;
- }
-
- public int getAge() {
-
- return Age;
- }
-
- //类属性,学校名称
- public static String school="北京";
-
- //类方法,学习
- public static void study()
- {
- String study="开始学习了!";
- System.out.println(study);
- }
-
- //对象方法:说话
- public void speak(String s)
- {
- System.out.println(s);
- }
- //对象方法:实现两个数的相加
- public void count(double c1,double c2)
- {
- System.out.println(c1+c2);
- }
-
- //对象方法:实现年龄长一岁
- public int ageAdd(int year) {
- Age=year+1;
- return this.Age+1;
- }
- public void show()
- {
- System.out.println("我的姓名是"+Name+",今年"+Age+",性别:"+Sex+",身高:"+height);
- }
- }

- package Student;
-
-
- public class Penpal extends Student{
- private String Sex;
- public String getSex(){
- return Sex;
- }
- public void setSex(String Sex){
- this.Sex=Sex;
- }
- }
-
- package Student;
- import Student.Penpal;
- import Student.Student;
-
- import static Student.Student.study;
- public class HelloWorld {
-
-
- public static void main(String[] args) {
-
- //类属性,学校名称
- System.out.println(Student.school);
-
- //类方法:学习
- study();
-
- //创建第一个实例:园子
- Student zhang=new Student();
- zhang.Age=9;
- zhang.height=175;
- zhang.Name="园子";
- zhang.Sex="男";
- System.out.println("姓名:"+zhang.Name+" 性别:"+zhang.Sex+"\t年龄:"+zhang.Age+"\t身高:"+zhang.height);
- //创建第二个实例:团后
- Student li=new Student();
- li.Name="团后";
- li.Age=15;
- li.height=198;
- li.Sex="女";
- System.out.println("姓名:"+li.Name+" 性别:"+zhang.Sex+"\t年龄:"+li.Age+"\t身高:"+li.height);
-
- //创建第三个实例
- Student p1=new Student("张老三","男",18,180);
- p1.speak("你好,我是新来的学生");
- //说话
- p1.show();
-
- //实现年龄的加一
- Student p2=new Student("王老五","女",10,158);
- p2.speak("你好,我是新来的学生");
- //实现年龄的加一
- p2.ageAdd(p2.Age);
- p2.show();
-
- //实现两个数的相加
- System.out.println("两个数的相加结果如下:");
- p2.count(23, 45);
-
- //实现对setter/getter的使用
- Penpal Student=new Penpal();
- Student.setSex("女");
- Student.setName("老纪");
- Student.setAge(12);
- Student.setHeight(156);
- System.out.println("姓名:"+Student.getName()+" "+"性别:"+Student.getSex()+" "+"年龄:"+Student.getAge()+" "+"身高:"+Student.getHeight()+"\n");
-
-
- }
- }
-
-

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。