public class A { public static int get(int n){ return n+10; } public int see(int n){ return n+10; } }
时间: 2024-02-15 13:03:26 浏览: 32
这是一个Java类 A,它包含两个方法:
1. `get(int n)` 是一个静态方法,它接收一个整数参数 n,将 n 加上 10 并返回结果。
2. `see(int n)` 是一个非静态方法,它接收一个整数参数 n,将 n 加上 10 并返回结果。
下面是一个示例代码,展示如何在另一个类中使用 A 类的这两个方法:
```
public class B {
public static void main(String[] args) {
int result1 = A.get(5); // 调用 A 类的静态方法 get()
System.out.println(result1); // 输出 15
A a = new A(); // 创建 A 类的实例
int result2 = a.see(5); // 调用 A 类的非静态方法 see()
System.out.println(result2); // 输出 15
}
}
```
在这个示例中,我们首先通过 `A.get(5)` 的方式调用了 A 类的静态方法 get(),并将返回值赋给 result1 变量,最后输出结果。接着,我们创建了 A 类的一个实例 a,并通过 `a.see(5)` 的方式调用了 A 类的非静态方法 see(),将返回值赋给了 result2 变量,最后输出结果。
希望这个示例能够帮助您理解如何在Java中使用静态方法和非静态方法。
相关问题
class Animal{ public static int get (int n) { return n+10; } public int see (int n) { return n+10; } } class Dog extends Animal { public static int get (int n) { return n*10; } public int see (int n) { return n*10; } } public class E { public static void main (String args []) { Animal animal = null; animal = new Dog (); System. out. printf (“%d:%d”, animal. get (10), animal. see (10)); } }详细解读这段代码
这段代码定义了一个Animal类,其中包含一个静态方法get和一个实例方法see。还定义了一个Dog类,它继承了Animal类,并且重写了get和see方法。最后定义了一个E类,并在其main方法中创建了一个Dog对象,并将其赋值给Animal类型的变量animal。然后调用animal对象的get和see方法,并输出结果。
在Animal类中,静态方法get返回传入参数n加上10的结果。实例方法see也返回传入参数n加上10的结果。
在Dog类中,静态方法get返回传入参数n乘以10的结果。实例方法see也返回传入参数n乘以10的结果。
在E类中,创建了一个Dog对象,并将其赋值给Animal类型的变量animal。虽然animal变量的静态类型是Animal,但实际上它指向的是一个Dog对象。因此,animal调用get方法时,会调用Dog类的get方法,返回传入参数n乘以10的结果;调用see方法时,也会调用Dog类的see方法,返回传入参数n乘以10的结果。最后输出结果20:100。
阅读程序题(给出【代码】注释标注的代码的输出结果) interface Com { int add(int a,int b); public static int get(int n){ return n; } public default int see(int n){ return n; } public default int look(int n){ return n; } } class A implements Com{ public int add(int a,int b) { return a+b; } public int see(int n){ return n+1; } } public class E { public static void main(String args[]) { A a = new A( ); int m = a.add(12,6); int n =Com.get(12); int t = a.see(6); int q = a.look(6); System.out.printf("%d:%d:%d:%d",m,n,t,q); //【代码】 } }
程序的输出结果为:
```
18:12:7:6
```
解释如下:
1. `int m = a.add(12,6);` 会调用 `A` 类中实现的 `add` 方法,计算 12+6=18,将结果赋值给变量 `m`。
2. `int n = Com.get(12);` 会直接调用 `Com` 接口中定义的静态方法 `get`,传入参数 12,将返回值 12 赋值给变量 `n`。
3. `int t = a.see(6);` 会调用 `A` 类中实现的 `see` 方法,将参数 6 加上 1,结果为 7,将结果赋值给变量 `t`。
4. `int q = a.look(6);` 会调用 `Com` 接口中默认实现的 `look` 方法,将参数 6 原样返回,结果为 6,将结果赋值给变量 `q`。
5. `System.out.printf("%d:%d:%d:%d",m,n,t,q);` 会按照格式输出变量 `m`、`n`、`t`、`q` 的值,以冒号分隔。因此程序的输出结果为 `18:12:7:6`。