版权声明:学习分享,共同进步 https://blog.csdn.net/Andrew_jdw/article/details/83024855
如果加上static即是静态方法或静态函数,就可以直接通过类名访问,在类内部也是可以直接访问。
如果没有static就是非静态方法,只能通过创建对象来访问。
案例:定义一个函数可以接收任意类型的图形对象,并且打印图形面积和周长。(采用多态的方式)
1.创建Myshape类
abstract class MyShape{
String name;
public MyShape(String name){
this.name = name;
}
public abstract void getArea();
public abstract void getLength();
}
2.创建Circle类继承Myshape类,由于Myshape是抽象类,所以需要将Myshape类中的方法进行实现。
class Circle extends MyShape{
public static final double PI = 3.14;
double r;
public Circle(String name, double r){
super(name);
this.r = r;
}
public void getArea(){
System.out.println(name+"的面积是:"+(PI*r*r));
}
public void getLength(){
System.out.println(name+"的周长是:"+(2*PI*r));
}
}
3.创建Rect类继承Myshape类
class Rect extends MyShape{
double wid;
double len;
public Rect(String name, double wid, double len){
super(name);
this.wid = wid;
this.len = len;
}
public void getArea(){
System.out.println(name+"的面积是:"+(wid * len));
}
public void getLength(){
System.out.println(name+"的周长是:"+(2*(wid +len)));
}
}
class Demo18{
public static void main(String[] args){
Circle c = new Circle("圆",3);
print(c);
}
public void print(MyShape s){// MyShape s = new Circle("圆",3);//如果不添加static
s.getArea();
s.getLength();
}
在编译时就会报错:Demo18.java:54: 错误: 无法从静态上下文中引用非静态 方法 print(MyShape) print(c);
print函数添加上static后可以成功编译。原因就是非静态函数不能直接调用。需要创建对象。如果非要不添加static可以采用如下方式:
class Demo{
//需求:定义一个函数可以接受任意类型的图形对象,并且打印图形面积和周长
public void print(MyShape s){// MyShape s = new Circle("圆",3);
s.getArea();
s.getLength();
}
}
class Demo18{
public static void main(String[] args){
Circle c = new Circle("圆",3);
Demo d = new Demo();
d.print(c);
}
}