Thinking in java之构造器
来源:互联网 发布:车铣复合手工编程例子 编辑:程序博客网 时间:2024/06/05 17:06
首先,我们来看看this关键字这个神奇的关键字:
1.我们都知道利用this关键字在构造方法中对成员进行初始化:
private String Name;private int Age;private String Sex;public first_one(String Name,int Age,String Sex) {this.Age=Age;this.Name=Name;this.Sex=Sex;}这是一种很常见的初始化方法。
下面介绍另一种this关键字的应用:
2.在构造器中调用构造器
可能为一个类写了多个构造器,有时可能想在一个构造器中调用另一个构造器,以避免重复代码。则可用this做到这一点。
贴出《Thingking in java》源代码(由于BZ未实现该书中的Print方法,故用..println方法来代替,实现打印):
//:initialization/Flower.java//Calling constructor with "this"import static net.mindview.util.Print.*;public class Flower{int petalCount=0;String s="initial value";Flower(int petals){petalCount=petals;print("Constructor w/ int arg only,petalCount="+petalCount);}Flower(String ss){print("Constructor w/ String arg only,s= "+ss);s=ss;}Flower(String s,int petals){this(petals);//! this(s);//Can't call two!this.s=s;print("String & int args");}Flower(){this("hi",47);print("default constructor (no args)");}void printPetalCount() {//! this(11);//Not inside non-constructor!print("petalCount= "+petalCount+" s= "+s);}public static void main(String[] args) {Flower x=new Flower();x.printPetalCount();}运行结果:
/* Constructor w/ int arg only,petalCount=47 String & int args default constructor (no args) petalCount= 47 s= hi*/其次,我们介绍构造器的初始化:
构造器的初始化顺序:
在类的内部,变量定义的先后顺序决定了初始化的顺序,贴出代码:
//initialization/OrderOfInitialization.java//Demonstrates initialization orderimport static net.mindview.util.Print.*;//When the constructor is called to create a Window object,you'll see a message:class Window{Window(int marker){print("Window("+marker+")");}class House{Window w1=new Window(1);//Before constructorHouse(){//Show that we're in the constructor:print("House()");w3=new Window(33);//Reinitialize w3}Window w2=new Window(2);//After constructorvoid f() { print("f()");}Window w3=new Window(3);//At end}public class OrderOfInitialization{public static void main(String[] args) {House h=new House();h.f();//Show that constructor is done}}执行结果:
/* Window(1) Window(2) Window(3) House() Window(33) f()*/注:我在编译的时候,当main方法中的static不去掉时就会报错,但是不知道什么原因,要是哪位友友知道希望能告诉我为啥,谢谢~
阅读全文
0 0
- Thinking in java 之:构造器
- Thinking in java之构造器
- 《Thinking in Java》笔记之调用构造器顺序
- Thinking in Java 构造器的调用顺序
- Thinking in Java 之String
- Thinking in Java之Interfaces
- Thinking in java之接口
- Java多线程之使用执行器(Executors)(Thinking in Java)
- 构造器内书写异常以及使用的注意事项---Thinking in java
- 《Thinking in Java》——构造器是private时如何创建对象?
- Thinking in java-26 构造函数多态
- Thinking in java笔记之控制程序流
- Thinking in Java笔记之初始化清理
- Thinking in Java 附录之编程准则
- Thinking in Java 附录之推荐书籍
- Thinking in Java 之String 格式化
- Thinking in Java 之String 正则表达式
- Thinking in java 之复用类 final关键字
- Java中访问权限控制
- 一个tomcat部署多个项目(同端口,多项目,不同访问路径)
- 基于SignalR的小型IM系统
- centos7安装mysql5.6
- 认识Java
- Thinking in java之构造器
- Reactjs入门官方文档(三)【components-and-props】
- 【2017_ICCV_DML]Smart Mining for Deep Metric Learning
- python函数语法学习
- Redis五种数据类型介绍
- sunny-ngrok 的配置及使用
- Intellij IDEA常用快捷键大全
- Hi3516A-常用指令和根文件目录详解
- 浅谈深度学习