对象封装(二)

本文介绍了Java中构造方法的重载概念,并通过一个具体示例展示了如何实现构造方法的重载,包括不同参数类型的构造函数的选择过程。此外,还强调了返回值类型不能作为方法重载的依据。

如在程序中不声明限制修饰,则默认当前类有效。
当其他类引用此类的时候,只有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()视为重复定义而编译失败;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值