关键字 this 与 static 及其内存解析
来源:互联网 发布:多益网络 训练营 编辑:程序博客网 时间:2024/05/22 03:34
一、this关键字
(1)在类的方法中定义使用的 this 关键字,代表使用该方法的对象的引用。
(2)当必须指出当前使用方法的对象是谁时要使用 this 。
(3)有时使用 this 可以处理方法中成员变量和参数重名的情况。
(4)this 可以看作是一个变量,它的值是当前对象的引用。
public class Leaf{int i = 0 ;Leaf (int i) {this.i = i;}Leaf increament () {i++;return this;}void print (){System.out.println("i = "+ i);}public satic void main (String[] args){Leaf leaf = new Leaf (100);leaf.increament().increament().print();}}
二、static关键字
(1)在类中,用 static 声明的成员变量为静态成员变量,它是该类的公用变量,在第一次使用时被初始化,对于该类的所有对象来说,static 成员变量只有一份
(2)用 static 声明的方法为静态方法,在调用该方法时,不会将对象的引用传递给它,所以在 static 方法中不可访问非 static 的成员。(静态方法不再是针对于某个对象调用,所以不能访问非静态成员)
(3)可以通过对象引用或类名(不需要实例化)访问静态成员
public class Cat {private static int sid = 0; //去掉static,则不能再用Cat.sid来访问private String name;int id;Cat(String name) {this.name = name;id = sid++;}public void info (){System.out.println("My name is "+name+"No."+id);}public static void main (String[] args){Cat.sid = 100;Cat mimi = new Cat("mimi");Cat pipi = new Cat("pipi");mimi.info();pipi.info();}}
0 0
- 关键字 this 与 static 及其内存解析
- this关键字与static关键字
- 【Java】this与static关键字
- 关键字static、super与this
- this关键字、static关键字
- this关键字static关键字
- java基础14-this与static关键字
- 【java基础知识】this 与 static 关键字
- Java基础语法之this关键字与static关键字
- static this,super关键字
- java this、static关键字
- 关键字static和this
- private ,this ,static 关键字
- 6-this、static关键字
- this、static关键字
- this,static关键字
- this 、static 关键字
- java 关键字this-static
- 文章标题
- 【Dongle】【Java】基础(三)之classpath
- SpriteFrameCache遇到的函数问题
- SlidingMenu (侧边栏)使用步骤
- dsp28335时钟 总结
- 关键字 this 与 static 及其内存解析
- docker出现Cannot connect to the Docker daemon. Is 'docker -d' running on this host?导致起不了服务
- (自认为)账户业务最佳结构
- RS485通信与Modbus协议
- Hardwood Species 字典树 poj 2418
- 剑指offer——面试题16:反转链表
- apk反编译和打包,签名
- Visual Studio 2015 Caffe配置
- 获取指定月的date类型的月初和月末