【问题标题】:How to call an Object's Method from another class without creating a sub-class and/or inheriting class?如何在不创建子类和/或继承类的情况下从另一个类调用对象的方法?
【发布时间】:2014-03-10 14:51:06
【问题描述】:

我一直在学习非常初级的基本代码。现在我终于开始涉足实际编写简单的程序,并且真的被卡住了。

  • 我正在编写一个由两个类组成的简单程序;人们, 主页。

  • 一旦程序运行,方法openApp()会从(MainPage Class)的main方法中调用。

    public static void main(String[] args) {
    
          openApp();                
    }
    
  • 接下来,当openApp()被调用时,用户可以通过输入相应的数字来选择三个菜单来选择去

    即1 = 新闻源,2 = 个人资料或 3 = 朋友。

公共类主页面{

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
                    }

    }
}
  • 如果用户选择“朋友”,则程序调用 from
    方法 People 类称为 friend(People name)in MainPage 类,打印出 people 对象的朋友。

我的尝试:

  if (optionSelected == 3) {
        people.friend();
                }

我得到的错误:

线程“main”java.lang.Error 中的异常:未解决的编译问题: 人无法解决

问题是我不想在 MainPage 中扩展 People 类并继承它的所有方法,但我仍然想从 People 类调用 Object 方法来打印 people 对象的朋友。

注意:以防万一有人想查看位于 People 类中的 friend(People people) 方法:

public void friend(People people) {
    System.out.println(people.friend);

【问题讨论】:

    标签: java class oop inheritance methods


    【解决方案1】:

    优秀的问题格式。

    您可以声明People 类型的Object,并使用它。

    示例

    public class MainPage
    {
        People people = new People();
    
        // .. Some code.
    
        if(optionSelected == 3) {
            people.friend();
        } 
    }
    

    说明

    您的friend 方法是instance method。这意味着为了访问它,您需要创建对象的一个​​实例。这是通过new 关键字完成的。其次,除非People 是某种形式的实用程序类,否则您的friend 方法应该更像:

     public void friend()
     {
         System.out.println(this.friend);
     }
    

    并且为了良好的代码设计,请记住您的MainPage 类正在输出给用户,因此您应该return 值而不是打印它。其次,你应该符合良好的命名标准,在Java中我们在获取类成员时使用get前缀。

    public void getFriend()
    {
        return this.friend;
    }
    

    MainPage 类中,你应该打印这个。

    if(optionSelected == 3)
    {
       System.out.println(people.getFriend());
    }
    

    【讨论】:

    • 感谢克里斯托弗的出色回答!真的很感激:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-19
    • 2022-11-21
    • 2014-03-24
    • 1970-01-01
    • 2017-08-23
    相关资源
    最近更新 更多