JAVA面向对象(this关键字, static关键字)

~this关键字

this的作用:

– this表示的是当前对象本身,

– 更准确地说,this代表当前对象的一个引用。

▪ 普通方法中使用this。

– 区分类成员属性和方法的形参.

– 调用当前对象的其他方法(可以省略)

– 位置:任意

▪ 构造方法中使用this。

– 使用this来调用其它构造方法

– 位置:必须是第一条语句

▪ this不能用于static方

法。(学完static,大家就知道为什么了!)

*this 测试代码

public class TestThis {
    int a,b,c;
    TestThis(){
        System.out.println("正要new一个Hello对象");
}
    TestThis(int a,int b){
                //Hello();   //这样是无法调用构造方法的!
                this();     //调用无参的构造方法,并且必须位于第一行!
                a = a;     //这里都是指的局部变量而不是成员变量
              this.a = a;//这样就区分了成员变量和局部变量. 这种情况占了this使用情况的大多数!
            this.b = b;
    }

    TestThis(int a,int b,int c){
        this(a,b); //调用无参的构造方法,并且必须位于第一行!
        this.c = c;
        
    }

        void sing(){}

        void chifan(){

            this.sing(); //sing();
            System.out.println("你妈妈喊你回家吃饭!");
        }
    public static void main(String[] args){
        TestThis hi = new TestThis(2,3);
        hi.chifan();
        }
}

~static关键字(概念)

在类中,用static声明的成员变量为静态成员变量 ,或者叫做: 类属性,类变量.

它为该类的公用变量,属于类,被该类的所有实例共享,在类被载入时被显式初始化,

对于该类的所有对象来说,static成员变量只有一份。被该类的所有对象共享!!

可以使用”对象.类属性”来调用。不过,一般都是用“类名.类属性”

static变量置于方法区中!

用static声明的方法为静态方法

不需要对象,就可以调用(类名.方法名)

在调用该方法时,不会将对象的引用传递给它,所以在static方法中不可访问非static的成员。

静态方法不能以任何方式引用this和super关键字

public class TestStatic {
    int a;
    static int width;
    static void gg(){
        System.out.println("gg");
    }
    void tt(){
        System.out.println("tt");
    }
    public static void main(String[] args){
        TestStatic hi = new TestStatic();
        TestStatic.width = 2;
        TestStatic.gg(); //gg();
        hi.gg();
        
        gg();
        //通过引用也可以访问static变量或static方法。不过,一般还是使用类名.static成员名来访问
    }
}

~ststic关键字(使用)

▪ 使用static声明的成员变量称为静态变量,

▪ 使用static声明的方法称为静态方法

▪ 静态变量不静态方法又称为类变量类方法

~静态属性的访问形式

– (1)对象名.属性

– (2)类名.属性

~ 静态方法

– 访问修饰符 static 返回值类型 方法名(){}

~访问形式

– (1)对象名.方法名();

– (2)类名.方法名();

//使用static统计在类中一共产生多个对象
public class StaticDemo{        //声明类

    static int count;//声明静态属性
    public StaticDemo(){    //无参构造方法
        count++;
        System.out.println("创建了"+count+"个对象");
    }
    public static void main(String[] args){

        new StaticDemo();    //创建匿名对象
        new StaticDemo();    //创建匿名对象
        new StaticDemo();    //创建匿名对象
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值