java-Java基础关键字this,supper,static的作用

java关键字:      this,supper

this: 当前/这个  

可修饰 属性/方法/构造器

修饰属性: 修饰成员变量(即 类变量)

代码:

public class User {

public int heda = 50;
public  void set(){
int heda = 10;
System.out.println("我是不加 [this] 输出结果: "+heda);
System.out.println("我是添加 [this.] 输出结果"+this.heda);
}}

 如果 当前类下的方法中  存在着与属性名相同的 (局部变量)  

不使用(this.)关键字修饰  那么调用只会是 此方法总存在的与属性名相同的变量;

使用 [this.]  关键字

如果 不存在与属性同名的变量   那么调用的是当前类的属性  

ps: 在调用属性时 是默认使用 [this.] 来调用的

 

 

修饰构造器:   格式为 this(参数名,......);     括号内的参数个数 根据自己需要调用的构造器参数个数 去判断     this调用构造器时   必修放在首行

代码:

public class User {
private String userName;
private Double height;
/*Integer 是 int 的包装类 等同于 int*/
private Integer age;

public User(){

}
User user = new User("person",19);
public User(String userName){
System.out.println("你好");
}

public User(String userName,Integer age){
this(userName);
this.age = age;
}}

 

 

 

 

 

修饰方法:

在当前类中调用本类方法时  默认使用[this.]修饰

 

 

 

supper 经常发生在父子类(即  继承中)

可修饰    属性 方法  构造器   

(作用基本于this相同)

修饰 属性

代表  父类中的属性  

修饰  方法  

代表   父类中的方法

修饰构造器

代表 父类构造器

 

static  静态的

static修饰的东西   会在类加载时  同时也会加载static修饰的 

可修饰   变量 方法  类  代码块  内部类

 

修饰方法 :

 

在静态方法中可以直接调用  同为静态的成员变量.但不可直接调用非静态的成员变量,但是可以通过 创建类对象调用

可以直接调用 其他静态方法 但不可调用非静态成员方法.   那你非要调用 方法同调成员变量一样

 

通过类名直接调用

public class Hello{

public  static String getMath(){

String str = "你好";

return str;

}

调用:

public class test {

public static void main(String [] args){

Hello.getMath();

}

}

输出结果 :    你好

 

posted @ 2021-06-09 22:31  知命-不知己命  阅读(181)  评论(0)    收藏  举报