Chinaunix首页 | 论坛 | 博客
  • 博客访问: 265562
  • 博文数量: 113
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1044
  • 用 户 组: 普通用户
  • 注册时间: 2015-02-15 16:09
文章分类

全部博文(113)

文章存档

2016年(5)

2015年(108)

我的朋友

分类: Java

2015-10-22 23:33:46

封装
构造方法
this用法,表示当前对象,方法和属性变量名一样时,必须使用this
static使用方法

点击(此处)折叠或打开

  1. /* static 静态成员变量称为类变量(类似于某些语言中的全局变量),而非静态的成员变量称为实例变量 */
  2. class Person {
  3.     String name;        // 定义name属性,此处暂不封装
  4.     int age;            // 定义age属性,此处暂不封装
  5.     static String country = "A城";        // 定义城市属性,有默认值
  6.     public Person(String name,int age) {// 通过构造方法设置
  7.         this.name = name;                    
  8.         this.age = age;        // 为age赋值
  9.     }
  10.     public void info() {        // 直接打印信息
  11.         System.out.println("姓名:"+ this.name + ",年龄:" + this.age + ",城市:"+ country);
  12.     }
  13. }
  14. public class Thisi{
  15.     public static void main(String args[]){
  16.         Person per1=new Person("张三",20);
  17.         per1.country="B城";
  18.         per1.info();
  19.         
  20.     }
  21. }



点击(此处)折叠或打开

  1. /* 使用this表示当前对象 */
  2. /* this最重要的特点就是表示当前对象 */
  3. /* 当参数名与成员变量名一样时,this不能省 */
  4. class Person{
  5.     String name;
  6.     void talk(String name){
  7.         System.out.println("my name is "+this.name);
  8.     }
  9.     
  10. }
  11. public class Thisi{
  12.     public static void main(String args[]){
  13.     Person p1=new Person();
  14.     Person p2=new Person();
  15.     p1.talk("canshu1");
  16.     p2.talk("canshu2");
  17.     }
  18. }


点击(此处)折叠或打开

  1. /* 构造方法 */
  2. /*类和方法名字一样,但是方法没有参数类型,前面只有一个public*/
  3. class Person {
  4.     public Person(String name,int age){            // 声明构造方法
  5.         System.out.println("姓名"+name+",年龄"+age);
  6.     }
  7. }
  8. public class Thisi {
  9.     public static void main(String args[]) {
  10.         Person per1=new Person("张三",48);
  11.     }
  12. }


点击(此处)折叠或打开

  1. /* 封装
  2. 使用setter及getter方法 */
  3. class Person {
  4.     private String name;
  5.     private int age;
  6.     public void tell() {
  7.         System.out.println("姓名:"+getName() +",年龄:"+ getAge());
  8.     }
  9.     public String getName() {
  10.         return name;
  11.     }
  12.     public void setName(String n) {
  13.         name = n;
  14.     }
  15.     public int getAge() {
  16.         return age;
  17.     }
  18.     public void setAge(int a) {
  19.         if (a>30&&a<130)
  20.         age = a;
  21.     }
  22. }
  23. public class Thisi{
  24.     public static void main(String args[]){
  25.         Person per1=new Person();
  26.         per1.setName("张三");
  27.         per1.setAge(50);
  28.         per1.tell();
  29.     }    
  30. }
阅读(1425) | 评论(0) | 转发(0) |
0

上一篇:C语言知识

下一篇:JAVA笔记3

给主人留下些什么吧!~~