封装性 匿名对象 构造函数
2015-10-14 12:27
288 查看
//封装性
class Person{
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String n) {
this.name = n;
}
public int getAge() {
return age;
}
public void setAge(int a) {
this.age = a;
}
public void tell(){
System.out.println("年龄"+getAge()+" "+"姓名"+getName());
}
public void tell2(int b){
System.out.print(b);
//return b;//不会被打印出来
}
}//可以右键sourse generate getters and setters直接获得
public class method {
public static void main(String[] args) {
/*Person pre=new Person();
pre.setAge(30);
pre.setName("张三");
pre.tell();*/
//匿名对象实验
new Person().setAge(44);
new Person().setName("张三");//匿名对象看起来无法调用setter和getter函数啊
new Person().tell();
new Person().tell2(33);
new Person().tell2(55);
}
}
构造函数
public Person(int a){//class创建的时候自动创建一个同名的构造函数,构造函数也可以重载,构造方法没有返回值
System.out.println(a);
class Person{
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String n) {
this.name = n;
}
public int getAge() {
return age;
}
public void setAge(int a) {
this.age = a;
}
public void tell(){
System.out.println("年龄"+getAge()+" "+"姓名"+getName());
}
public void tell2(int b){
System.out.print(b);
//return b;//不会被打印出来
}
}//可以右键sourse generate getters and setters直接获得
public class method {
public static void main(String[] args) {
/*Person pre=new Person();
pre.setAge(30);
pre.setName("张三");
pre.tell();*/
//匿名对象实验
new Person().setAge(44);
new Person().setName("张三");//匿名对象看起来无法调用setter和getter函数啊
new Person().tell();
new Person().tell2(33);
new Person().tell2(55);
}
}
构造函数
public Person(int a){//class创建的时候自动创建一个同名的构造函数,构造函数也可以重载,构造方法没有返回值
System.out.println(a);
相关文章推荐
- C++中拷贝构造函数的应用详解
- 构造函数不能声明为虚函数的原因及分析
- 深入讲解C++中的构造函数
- C++类成员构造函数和析构函数顺序示例详细讲解
- c++基础语法:构造函数与析构函数
- JavaScript 构造函数 面相对象学习必备知识
- JavaScript面向对象设计二 构造函数模式
- Javascript面向对象编程(二) 构造函数的继承
- 成员初始化列表与构造函数体中的区别详细解析
- C#中私有构造函数的特点和用途实例解析
- C#中派生类调用基类构造函数用法分析
- C#静态构造函数用法实例分析
- javascript 静态对象和构造函数的使用和公私问题
- Javascript 使用function定义构造函数
- JavaScript中的普通函数与构造函数比较
- jQuery构造函数init参数分析续
- jquery 构造函数在表单提交过程中修改数据
- php中拷贝构造函数、赋值运算符重载
- JS特殊函数(Function()构造函数、函数直接量)区别介绍
- 不用构造函数(Constructor)new关键字也能实现JavaScript的面向对象