类方法和实例方法的使用区别

43 阅读1分钟

一、类方法可以直接访问类成员,不可以直接访问实例成员,只可以间接访问。
二、实例方法中既可以直接访问类成员,也可以直接访问实例成员。
三、实例方法中可以出现this,类方法中不可以出现this关键字。 this:
this代表当前对象
实例方法:❤有对象------->可以有this
类方法:💔没有对象------->不可以有this

//静态变量
public static String schoolName="北京大学";
public static void place(){
Sysyem.out.println("我们都在清华好好学习");
 }
 
 //实例变量
 private String name;
 
 //实例方法
  private void printInfo(){
  System.out.println("名字叫"+name);  
 
// 二、实例方法中既可以直接访问类,也可以直接访问实例成员。
   System.out.println("名字叫:"+name); //访问实例成员 
   System.out.println("学校名字叫:"+schoolName);  //访问类成员
   
 public class void main(String[] args){
//一、类方法可以不可以直接访问实例成员,只可以间接访问。 
  Test t=new Test();//创建对象
  t.testNoStatic();
 }

public static void staticTest(){
//一、类方法可以直接访问类成员,不可以直接访问实例成员
 Sysyem.out.println(schoolname);
 place();

//访问实例成员
//Sysyem.out.println(name);//错误:
//printInfo();//错误:

//类方法中不可以出现this关键字
 System.out.println(this.name);
 }

//实例方法中可以出现this,
 public void testNoStatic(){
 System.out.println(this.name);
 this.printInfo();
 }
}
}