java主类调用其他类
时间: 2023-09-25 16:11:22 浏览: 88
在 Java 中,要调用其他类,需要使用对象来访问其成员变量和方法。下面是一个例子:
假设有两个类,一个是主类 MainClass,另一个是其他类 OtherClass。
OtherClass.java:
```
public class OtherClass {
public void sayHello() {
System.out.println("Hello from OtherClass!");
}
}
```
MainClass.java:
```
public class MainClass {
public static void main(String[] args) {
// 创建 OtherClass 的对象
OtherClass oc = new OtherClass();
// 调用 OtherClass 的方法
oc.sayHello();
}
}
```
在主类中,我们创建了 OtherClass 的对象 oc,并通过该对象来访问其方法 sayHello()。注意,要访问其他类的成员变量和方法,需要在前面加上对象名。
相关问题
java在主类中调用方法
Java中在主类中调用方法需要先定义该方法并在主类中实例化该方法,然后通过实例化的方法调用该方法。
例如,在主类中定义一个方法:
```java
public class Main {
public static void main(String[] args) {
MyClass myClass = new MyClass();
myClass.myMethod();
}
}
class MyClass {
public void myMethod() {
System.out.println("Hello World!");
}
}
```
在上述代码中,我们定义了一个名为`myMethod()`的方法并在`Main`类中实例化了`MyClass`类,最后通过实例化的`myClass`对象调用了`myMethod()`方法。在`myMethod()`方法中,我们打印了一条简单的消息。
运行上述代码,输出如下:
```
Hello World!
```
在java的一个文件中,调用其他类的方法,必须在主类中调用
可以在主类中调用其他类的方法,也可以在其他类中调用其他类的方法,只需要在调用时使用正确的语法即可。例如,在主类中调用其他类的方法,可以使用类名加方法名的方式,如:ClassName.methodName()。在其他类中调用其他类的方法,可以使用对象名加方法名的方式,如:objectName.methodName()。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)