知识总结:
static 加在属性前面:类属性
加在方法前面:类方法:
不能加在类前面:不存在静态类!
不能加在方法内的局部变量前:局部变量不具有静态,只有final!(如下)
和类属性的调用方法相似
类方法的调用:(推荐第二种类名.+方法)
在成员方法当中,是直接可以访问类的静态成员的!(如下)
Cat.java
CatTest.java(主要看运行结果)
相反,1.在静态的成员方法当中不能够访问普通的成员方法,属性!(除非,将要访问的那个方法,属性转换成静态的)!
2.静态方法中不能用this!
但是如果非要调用,只能通过内部对象实例化后,再调用!
以上代码:
Cat.java文件
package com.imooc.animal;
/**
* 宠物猫类
* @author zhangziwei
*
*/
public class Cat {
private String name;
private int month;
private double weight;
private String species;
//static :表示静态成员、类成员
public static int price;
public Cat(){
System.out.println("宠物猫!");
}
public void setName(String name){
this.name=name;
}
public String getName(){
return "我是一只名叫"+this.name+"的猫咪";
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
if(month<=0)
{
System.out.println("输入信息错误,宠物猫的年龄必须大于0");
}else
this.month = month;
}
public String getSpecies() {
return species;
}
public void setSpecies(String species) {
this.species = species;
}
//在当前类下面可以调用任意方法(包括静态),和热议属性(包括静态)
public void run(){
eat();
this.name="牛牛";
this.price=20;
System.out.println("售价是"+this.price+"的小猫"+this.name+"会跑");
}
public void run(String name){
System.out.println(name+"快跑!");
}
//类方法
public static void eat(){
//静态方法中不能直接访问同一类的非静态成员,只能直接调用同一个类当中的静态成员
//如果非要调用只能通过对象实例化后,对象.方法使用(同理属性)
Cat temp=new Cat();
temp.run();
temp.name="小冰";
this.name="花花";//不能用this
name=小胖;//非静态
price=1500;//静态
System.out.println("小猫吃鱼");
}
}
package com.imooc.CatTest;//定义包
import com.imooc.animal.*;
public class Test {
public static void main(String[] args) {
Cat one =new Cat();
one.setName("花花");
one.setMonth(2);
one.setSpecies("英国短毛");
one.price=2000;
Cat.price=3000;//使用静态的方法调用
one.run();
}
}
父类中的静态方法不能被子类重写!