不能举个例子,JAVA静态方法。
时间: 2024-05-23 08:15:21 浏览: 14
当然可以举例子。举一个简单的例子,比如有一个类叫做Person,其中有一个静态方法叫做getAge(),用于返回人的年龄。在这个静态方法里面,不能访问实例变量,只能访问静态变量。例如:
public class Person {
static int age = 25;
public static int getAge() {
return age;
}
}
在这个例子中,getAge()方法访问了静态变量age,而不能访问任何实例变量。
相关问题
Java接口中的静态方法和默认方法举个例子
静态方法的例子:
```java
public interface MyInterface {
static void myStaticMethod() {
System.out.println("This is a static method in MyInterface");
}
}
public class MyClass implements MyInterface {
public static void main(String[] args) {
MyInterface.myStaticMethod(); // 调用静态方法
}
}
```
默认方法的例子:
```java
public interface MyInterface {
default void myDefaultMethod() {
System.out.println("This is a default method in MyInterface");
}
}
public class MyClass implements MyInterface {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.myDefaultMethod(); // 调用默认方法
}
}
```
请举一个静态方法的例子
一个静态方法的例子是Java中的Math类中的静态方法,例如:
```
public class Main {
public static void main(String[] args) {
double x = 5.5;
double y = 4.0;
// 使用Math类中的静态方法计算x和y的最大值和最小值
double max = Math.max(x, y);
double min = Math.min(x, y);
System.out.println("最大值为:" + max);
System.out.println("最小值为:" + min);
}
}
```
在上述代码中,我们使用了Math类中的静态方法max和min来计算两个数的最大值和最小值。由于max和min是静态方法,我们可以直接通过类名来调用这些方法,而不需要先创建Math类的实例。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)