如在程序中不声明限制修饰,则默认当前类有效。
当其他类引用此类的时候,只有public可用。
构造方法重载:
public Somese(int a)
{
if(a>0){this.a=a;}
}
public Somese(int a,String text)
{
if(a>0){this.a=a;}
if(text!=null){
this.text=text;
}
根据参数类型选择使用哪一个构造函数。
完整代码:
package cc.openhome;
public class Somese {
private int a=10;
private String text="n.a.";
int getA()
{
return a;
}
String getText()
{
return text;
}
public Somese(int a)
{
if(a>0){this.a=a;}
}
public Somese(int a,String text)
{
if(a>0){this.a=a;}
if(text!=null){
this.text=text;
}}
public static void main(String[] args) {
Somese some=new Somese(1);
System.out.printf("Somese(%d)%n", some.getA());
Somese come=new Somese(1,"string");
System.out.printf("Somese(%d,%s)%n", come.getA(),come.getText());
}
}
结果:
特别说明:
返回值类型不可以作为方法重载依据。编译程序会将两个someMethod()视为重复定义而编译失败;
本文介绍了Java中构造方法的重载概念,并通过一个具体示例展示了如何实现构造方法的重载,包括不同参数类型的构造函数的选择过程。此外,还强调了返回值类型不能作为方法重载的依据。
1127

被折叠的 条评论
为什么被折叠?



