java笔记 类成员的默认值

一.成员属性的默认值

如果不进行构造的话,系统的默认构造函数给成员属性赋值为0

class A
{
    
    
    int x;
    int y;
}

public class test
{
    
    
    public static void main(String args[])
    {
    
    
        A a = new A();
        System.out.println(a.x + " " + a.y);
    }
}

在这里插入图片描述

二.构造函数的参数默认this

class A
{
    
    
    int x;
    int y;

    A()
    {
    
    
        x = 0;
        y = 0;
    }

    A(int x, int y)
    {
    
    
        x = x;
        y = y;
    }
}

public class test
{
    
    
    public static void main(String args[])
    {
    
    
        A a = new A(3,4);
        System.out.println(a.x + " " + a.y);
    }
}

在这里插入图片描述

在有参构造函数中,形参和成员属性是一样的
如果直接写成x = x; y = y;
在系统看来是默认的this
也就是this.x = this .x输出自然是0


但如果是这样

 A(int x, int y)
    {
    
    
        this.x = x;
        this.y = y;
    }

系统能够区分哪个是成员属性,哪个是形参
就能输出3,4
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/yogur_father/article/details/108845755
今日推荐