java 类与对象
1.在定义变量时,java要求必须显示初始化变量。
比如以下代码无法通过编译:
1 2 3 4 5 6 7 | public class Twst{ public static void main(String[] wrgs) { int value; System. out .println(value); } } |
1 2 3 4 5 6 7 | public class Twst{ public static void main(String[] wrgs) { int value=100; System. out .println(value); } } |
这样写才能运行。
下面这个 也是不能运行,因为对象变量如果不引用一个真实的对象,则必须声明为null;
1 2 3 4 5 6 7 | public class Test{ public static void main(String[] args) { MyClass obj ; System. out .println(obj.toString()); } } |
下面这个才能运行:
1 2 3 4 5 6 7 | public class Test{ public static void main(String[] args) { MyClass obj = null ; System. out .println(obj.toString()); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | public class ert { public static void main(String[] args ) { Foo obj1= new Foo(); } } class Foo{ int value; public Foo( int initvalue) { value =initvalue; } } |
上面这些代码出什么问题?哪出错了?
因为是如果类提供了一个自定义的构造方法,将导致系统不在提供默认的构造方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | package wer; public class ert { public static void main(String[] args ) { int a=0; Foo obj1= new Foo (a); } } class Foo{ int value; public Foo( int initvalue) { value =initvalue; } } |
这样写就对了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | public class ert { public static void main(String[] args ) { InitiazeBlockClass obj= new InitiazeBlockClass(); System. out .println(obj.field); obj= new InitiazeBlockClass(300); System. out .println(obj.field); } } class InitiazeBlockClass{ { field=200; } public int field=100; public InitiazeBlockClass( int value) { value= this .field; } public InitiazeBlockClass() { } } |
如果一个类中既有初始化块,又有构造方法,同时还设定了字段的初始值,谁说了算?
就像上面的代码中。
执行 类成员定义时指定的默认值或类的初始化块,到底执行哪一个要看哪一个“排在前面”。
执行类的构造函数。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)