java中构造方法实例(含注释)

来源:互联网 发布:破何破解网页直播源码 编辑:程序博客网 时间:2024/05/03 21:23
package com.neusoft.xf;
class Person{//创建类,类中有什么,有属性(格式为:数据类型+属性名)
        private String name;
        private int age;
        public Person(String n,int a){//构造方法,构造方法时也是一样的,该方法中,有数据类型,属性值,声明构造方法为类中的属性初始化
            this.setName(n);//这两段的作用是什么?
            this.setAge(a);//这两段的作用是什么?
    }
        public void setName(String n){
            name=n;
        }
        public String getName(){
            return name;
        }
        public void setAge(int a){
            age=a;
        }
        public int getAge(){
            return age;
        }
        public void tell(){
            System.out.println("姓名"+this.getName()+"年龄"+this.getAge());
            //为什么要用this
        }
}

public class Consdemo {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Person per=null;
        per = new Person("张三",30);//为什么这段方法内要写入属性值?
        per.tell();//为什么这里还要调用方法这个tell方法?,tell方法在这整段代码中又有什么用?
    }

}
/**
 * 构造方法时,方法名必须与类名一致,构造方法其实跟以往的面向对象差不多,然后方法中的()只有数据类型和属性值,不可能有其他的
 * */
0 0