1.java 中三种方法的调用

1.1.普通类:实例化一个该类的对象,然后通过对象访问。例如:

 public  classs A{//实例方法(成员方法)
          public void method 1(){
                   System.out.println("我是A类的方法1");
          }
}
public static void main(String[] args){
          A a=new A();//实例化一个对象
          a.method1();
}

1.2、静态类:可以通过类名直接访问,而不用实例化对象。例如:

public  class static A{//类方法(静态方法)
         public static void method1(){
                    System.out.pringtln("我是A类的方法1")
         }
}
public static void main(String[] args){
          A.method 1 ();//静态方法的调用:类名.方法名
}
1.3构造方法的调用
  1. public class A{  
  2.    public A(){  
  3.       System.out.println("调用了无参的构造函数");  
  4.    }  
  5.    public A(String mess){  
  6.       System.out.println("调用了有参的构造函数\n"+  
  7.          "参数内容为:"+mess);  
  8.    }  
  9. }  

 Test.java

  1. public class Test{  
  2.    public static void main(String [] args){  
  3.        A a_1=new A();//调用无参的构造函数  
  4.        A a_2=new A("Hello");//调用有参的构造函数  
  5.    }  
下面是三种方法调用的实例:
public class Trangle {
    static double a;
    static double b;
    static double c;
    static double p;

    int Tra;

    public Trangle() {

    }

    // 计算任意三点组成的三角形面积(使用三种方法计算)
    Trangle(Point p1, Point p2, Point p3) {

        a = Math.sqrt((p2.y - p1.y) * (p2.y - p1.y) + (p2.x - p1.x) * (p2.x - p1.x));
        b = Math.sqrt((p3.y - p2.y) * (p3.y - p2.y) + (p3.x - p2.x) * (p3.x - p2.x));
        c = Math.sqrt((p3.y - p1.y) * (p3.y - p1.y) + (p3.x - p1.x) * (p3.x - p1.x));
        p = (a + b + c) / 2;

        Tra = (int) Math.sqrt(p * (p - a) * (p - b) * (p - c));
    }

    public static int Tra1(double p, double a, double b, double c) {

        return (int) Math.sqrt(p * (p - a) * (p - b) * (p - c));
    }

    public int Tra2(double p, double a, double b, double c) {
        return (int) Math.sqrt(p * (p - a) * (p - b) * (p - c));
    }

    public static void main(String[] args) {
        Point p1 = new Point(2, 2);
        Point p2 = new Point(7, 8);
        Point p3 = new Point(39, 0);

        Trangle t = new Trangle(p1, p2, p3);
        System.out.println("构造方法计算,三角形的面积是:" + t.Tra);

        Trangle t1 = new Trangle();
        int s1 = t1.Tra2(p, a, b, c);

        System.out.println("对象方法计算,三角形的面积是:" + s1);

        int s2 = Trangle.Tra1(p, a, b, c);
        System.out.println("类方法计算,三角形的面积是:" + s2);

    }

}
View Code

相关文章: