定义
实例方法:可以对当前对象的实例变量进行操作,也可以对类变量进行操作,由实例对象调用。
类方法:不能访问实例变量,只能访问类变量。由类名或者实例对象调用,不能出现this或者super关键字。
Demo
package com.lanjerry;
public class Demo0717 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
People p1=new People("小明",18,100);
p1.show();
People p2=new People("小明",18,200);
p1.show();
p2.show();
p1.change(300);
p1.show();
p2.change(400);
p1.show();
p2.show();
}
}
class People{
String name;
int age;
static int weight;
People(String name,int age,int weight)
{
this.name=name;
this.age=age;
this.weight=weight;
}
public void show()
{
System.out.println("name is:"+this.name+" age is:"+this.age+" weight is:"+this.weight);
}
public static void change(int weight)
{
//this.weight=weight;//报错,内容:Cannot use this in a static context
People.weight=weight;
}
}
Result
name is:小明 age is:18 weight is:100
name is:小明 age is:18 weight is:200
name is:小明 age is:18 weight is:200
name is:小明 age is:18 weight is:300
name is:小明 age is:18 weight is:400
name is:小明 age is:18 weight is:400