我一直在学习非常初级的基本代码。现在我终于开始涉足实际编写简单的程序,并且真的被困住了。
我正在编写一个包含两个类的简单程序;人们, 主页。
程序运行后,
openApp()
方法在(MainPage 类)的主要方法中被调用。public static void main(String[] args) { openApp(); }
接下来,当
openApp()
被调用时,用户有三个菜单可供选择,通过输入相应的数字来选择它们即1 = Newsfeed,2 = Profile 或 3 = Friends。
公共(public)类主页面{
public static void openApp() {
System.out.println("Welcome to App!");
System.out.println();
System.out.println("To Select Option for:");
System.out.println("Newsfeed : 1");
System.out.println("Profile : 2");
System.out.println("Friends : 3");
System.out.println("Enter corresponding number: ");
int optionSelected = input.nextInt();
switch (optionSelected) {
case 1: System.out.println("NewsFeed");
break;
case 2: System.out.println("Profile");
break;
case 3: System.out.println("Friends");
break;
if (optionSelected == 3) {
people.friend();// Is it possible to write: friend() from "People" Class without extending to People Class
}
}
}
- 如果用户选择“ friend ”,程序将调用来自的方法
名为friend(People name)
MainPage 类的 People 类打印出 people 对象的 friend 。
我的尝试:
if (optionSelected == 3) {
people.friend();
}
我得到的错误:
Exception in thread "main" java.lang.Error: Unresolved compilation problem: people cannot be resolved
问题是我不想在 MainPage 中扩展 People 类并继承它的所有方法,但我仍然想从 People 类调用一个 Object 方法来打印 people 对象的 friend 。
注意:以防万一有人想查看 People 类中的 friend(People people)
方法:
public void friend(People people) {
System.out.println(people.friend);
最佳答案
出色的问题格式。
您可以声明一个People
类型的Object
,然后使用它。
例子
public class MainPage
{
People people = new People();
// .. Some code.
if(optionSelected == 3) {
people.friend();
}
}
解释
您的 friend
方法是一个实例方法
。这意味着为了访问它,您需要创建对象的实例。这是通过 new
关键字完成的。其次,除非 People
是某种形式的实用程序类,否则您的 friend
方法应该更像是:
public void friend()
{
System.out.println(this.friend);
}
为了良好的代码设计,请记住您的 MainPage
类正在向用户输出,因此您应该返回
值而不是打印它。其次,您应该遵循良好的命名标准,在 Java
中,我们在获取类成员时使用 get
前缀。
public void getFriend()
{
return this.friend;
}
在 MainPage
类中,您应该打印它。
if(optionSelected == 3)
{
System.out.println(people.getFriend());
}
关于java - 如何在不创建子类和/或继承类的情况下从另一个类调用对象的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21725227/