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()
    {
         
    }
    }
    

  如果一个类中既有初始化块,又有构造方法,同时还设定了字段的初始值,谁说了算?

就像上面的代码中。

执行 类成员定义时指定的默认值或类的初始化块,到底执行哪一个要看哪一个“排在前面”。

执行类的构造函数。

 

posted @   南北啊  阅读(14)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
1 2 3
4
点击右上角即可分享
微信分享提示