Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Có thể nạp chồng hoặc ghi đè phương thức static trong Java?


Phương thức static trong Java có thể nạp chồng (overload). Nhưng có điều kiện: hai phương thức không thể nạp chồng nếu chúng chỉ khác nhau bởi từ khóa static.

Xem ví dụ:

Ví dụ

public class Demo{    public static void test(){       System.out.println("Demo class test function has been called");    }    public static void test(int val){       System.out.println("Demo class test function with parameter has been called");    }    public static void main(String args[]){       System.out.println("In the main class, Demo functions being called");       Demo.test();       Demo.test(57);    } }

Kết quả

In the main class, Demo functions being called Demo class test function has been called Demo class test function with parameter has been called

Lớp Demo chứa hàm test in thông báo. Hàm test khác với tham số integer. Thông báo liên quan trong thân hàm. Trong main, test gọi không tham số và với tham số integer. Thông báo hiển thị trên console.

Phương thức static trong Java không thể ghi đè (override). Phương thức static cùng signature có thể định nghĩa trong lớp con, nhưng không phải đa hình runtime. Do đó, override không thể. Ví dụ:

Ví dụ

class base_class{    public static void show(){       System.out.println("Static or class method from the base class");    }    public void print_it(){       System.out.println("Non-static or an instance method from the base class");    } } class derived_class extends base_class{    public static void show(){       System.out.println("Static or class method from the derived class");    }    public void print_it(){       System.out.println("Non-static or an instance method from the derived class");    } } public class Demo{    public static void main(String args[]){       base_class my_instance = new derived_class();       System.out.println("Base class instance created.");       my_instance.show();       System.out.println("Function show called");       my_instance.print_it();       System.out.println("Function print_it called");    } }

Kết quả

Base class instance created. Static or class method from the base class Function show called Non-static or an instance method from the derived class Function print_it called

Lớp cơ sở có hàm static show in thông báo. Hàm print_it hiển thị thông báo. Lớp dẫn xuất kế thừa hai hàm. Lớp Demo chứa main tạo thể hiện lớp cơ sở kiểu lớp dẫn xuất. Thông báo hiển thị trên console.