免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 6817 | 回复: 2

关于构造函数 [复制链接]

论坛徽章:
2
2015年迎新春徽章
日期:2015-03-04 10:01:44程序设计版块每日发帖之星
日期:2015-06-28 22:20:00
发表于 2016-02-16 20:51 |显示全部楼层
class human{
        int age;
        human(){
                age=1;
                System.out.println("Human");
        }
}

class boy extends human{
        boy(){
                System.out.println("boy");
        }
}
public class test{


        /**
         * @param args
         */
        public static void main(String[] args) {
                // TODO Auto-generated method stub
                human h=new human();
                System.out.println(h.age);
                boy b=new boy();
               
                                    
                                    
        }
}

如果将构造函数human()和boy()定义为void human()和void boy()。则构造函数不会运行,这是什么原因?

论坛徽章:
0
发表于 2016-03-07 16:15 |显示全部楼层
构造函数是不能有返回值的
即使是void也不行
这是语言的规定

论坛徽章:
0
发表于 2016-05-04 13:13 |显示全部楼层
构造函数必须和类名同名,且没有返回值,否则编译器就不能晓得这个函数是构造函数了,添加void 相当于重新声明了成员函数,这个时候不是构造函数没有运行,而是执行了默认的构造函数;
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP