共计 1411 个字符,预计需要花费 4 分钟才能阅读完成。
构造方法写法
构造方法特征
无参的构造方法
/javaDemo2/src/com/imooc/Telphone.java
package com.imooc;
public class Telphone {
public Telphone() {
System.out.println(“ 无参的构造方法 ”);
}
}
/javaDemo2/src/com/imooc/InitailTelphone.java
package com.imooc;
public class InitailTelphone {
public static void main(String[] args) {
// TODO Auto-generated method stub
Telphone phone =new Telphone();
}
}
有参的构造方法
/javaDemo2/src/com/imooc/Telphone.java
package com.imooc;
import com.sun.glass.ui.Screen;
public class Telphone {
float screen;
float cpu;
public Telphone() {
System.out.println(“ 无参的构造方法 ”);
}
public Telphone(float newScreen,float newCpu) {
screen = newScreen;
cpu = newCpu;
System.out.println(“ 有参的构造方法 ”);
}
}
/javaDemo2/src/com/imooc/InitailTelphone.java
package com.imooc;
public class InitailTelphone {
public static void main(String[] args) {
// TODO Auto-generated method stub
Telphone phone =new Telphone();
Telphone phone2 =new Telphone(5.0f,1.4f);
}
}
构造方法给对象的属性一个合理的值
/javaDemo2/src/com/imooc/Telphone.java
package com.imooc;
import com.sun.glass.ui.Screen;
public class Telphone {
float screen;
float cpu;
public Telphone() {
System.out.println(“ 无参的构造方法 ”);
}
public Telphone(float newScreen,float newCpu) {
if(newScreen <3.5f) {
System.out.println(“ 你的参数有误 ”);
screen = 3.5f;
}
screen = newScreen;
cpu = newCpu;
System.out.println(“ 有参的构造方法 ”);
}
}
/javaDemo2/src/com/imooc/InitailTelphone.java
package com.imooc;
public class InitailTelphone {
public static void main(String[] args) {
// TODO Auto-generated method stub
Telphone phone =new Telphone();
Telphone phone2 =new Telphone(1.5f,1.4f);
}
}
效果