class A { public: void func1() { }; static void func2(){ }; };
时间: 2024-02-15 08:41:04 浏览: 117
This code defines a class named A with two methods: func1 and func2.
func1 is a non-static method, which means it can only be called on an instance of the A class. It doesn't take any parameters and doesn't return anything. It's empty in this case, but it could contain any kind of code.
func2 is a static method, which means it can be called on the A class itself, without requiring an instance of the class. It also doesn't take any parameters and doesn't return anything. It's also empty in this case, but could contain any kind of code.
The access modifier for both methods is "public", which means they can be called from outside the class.
相关问题
class Father{ public void func1() { func2();} class Father { public void func1() { func2(); } public void func2() { System.out.println("AAA"); }}class Child extends Father { public void func1(int i) { System.out.println("BBB"); } public void func2() { System.out.println("CCC"); }}public class PolymorphismTest { public static void main(String[] args) { Child child = new Child(); Father father = new Father(); child.func1(); child.func2(); father.func1(); father.func2(); }}打印结果
这段代码存在语法错误,无法编译通过。我做了一些修改,修改后的代码如下:
```
class Father {
public void func1() {
func2();
}
public void func2() {
System.out.println("AAA");
}
}
class Child extends Father {
public void func1(int i) {
System.out.println("BBB");
}
public void func2() {
System.out.println("CCC");
}
}
public class PolymorphismTest {
public static void main(String[] args) {
Child child = new Child();
Father father = new Father();
child.func1(1);
child.func2();
father.func1();
father.func2();
}
}
```
运行这段代码会输出以下结果:
```
BBB
CCC
AAA
AAA
```
解析:
1. 首先创建一个 Child 对象 child 和一个 Father 对象 father。
2. 调用 child.func1(1) 时,因为 Child 类有 func1(int i) 方法,所以直接调用 Child 类的 func1(int i) 方法,打印 "BBB"。
3. 调用 child.func2() 时,因为 Child 类有 func2() 方法,所以直接调用 Child 类的 func2() 方法,打印 "CCC"。
4. 调用 father.func1() 时,因为 Father 类有 func1() 方法,所以直接调用 Father 类的 func1() 方法,而 Father 类的 func1() 方法中又调用了 func2() 方法,所以打印 "AAA"。
5. 调用 father.func2() 时,因为 father 是 Father 类的对象,所以直接调用 Father 类的 func2() 方法,打印 "AAA"。
class A { public void func1() { System.out.print("A func1 is calling! "); } } class B extends A { public void func1() { System.out.print("B func1 is calling! "); } public void func2() { System.out.print("B func2 is calling! "); } } class C { public static void main(String[] args) { A a = new B(); a.func1(); a.func2(); } }
这段代码会编译错误,因为 `A` 类中没有定义方法 `func2()`,但是在 `main()` 方法中,将 `B` 类的对象 `b` 强制转换为 `A` 类的对象 `a`,然后尝试调用 `a` 对象的 `func2()` 方法,这是不允许的。
如果将 `a.func2()` 这行代码删除,程序的输出结果将是:
```
B func1 is calling!
```
首先,在 `main()` 方法中创建了一个 `B` 类的对象 `b`,然后将其强制转换为 `A` 类的对象 `a`。
接着,调用 `a.func1()` 方法,由于 `B` 类重写了 `func1()` 方法,因此会调用 `B` 类中的 `func1()` 方法,输出 `B func1 is calling!`。
因此,最终的输出结果是 `B func1 is calling!`。
阅读全文