静态变量、静态方法
1.静态变量
静态变量是属于类的,而不是属于类创建的对象
public static int num;
public static String s;
2.静态方法
静态方法只能访问类的静态变量或调用类的静态方法。
静态方法通常作为工具方法使用,当其被其它类使用时,不需要创建类的实例
class Difference{
public static void main(String[] args){
display();
Difference t = new Difference();
t.show();
}
// 静态方法
static void display(){
System.out.println("Amazing!");
}
// 普通方法
voic show(){
System.out.println("Awesome!");
}
接口和类
1.接口
1.接口之间可以继承和扩展
2.一个类可以实现多个接口
3.一个接口可以有多种实现类
2.使用静态工厂方法可以避免客户知道具体子类名称
举例来说
public class FastMyString implements MyString{
...
}
客户端具体实现时
MyString s = new FastMyString(true); //知道具体实现类的名字
为了避免这种情况发生
public interface MyString{
// 在接口里定义子类返回
public static MyString valueOf(boolean b){
return new FastMyString(true);
}
}
MyString s = MyString.valueOf(true);
使用default关键字
在接口统一实现某些功能,无需在各个类中重复使用它
public interface Example{
default int method1(int a){...}
static int method2(int b){...}
public int method3();
}
public class C implements Example{
@Override
public int method3(){...}
public static void main(String[] args){
Example.method2(2);
C c = new C();
c.method1(1);
c.method3();
}
}