Java 如何在不创建子类和/或继承类的情况下从另一个类调用对象的方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21725227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:20:32  来源:igfitidea点击:

How to call an Object's Method from another class without creating a sub-class and/or inheriting class?

javaclassoopinheritancemethods

提问by user3289740

I've been learning basic code at a very beginner level. Now I'm finally starting to dabble in actually writing simple programs, and got really stuck.

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

  • I'm writing a simple a program that consists of two classes; People, MainPage.

  • Once the program runs, the method openApp()is called in main method from (MainPage Class).

    public static void main(String[] args) {
    
          openApp();                
    }
    
  • Next, when the openApp()is called, the user has three menus to choose to go to that are selected by entering the corresponding number

    i.e. 1 = Newsfeed, 2 = Profile or 3 = Friends.

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

  • 程序运行后,该方法openApp()将在主方法(MainPage 类)中调用。

    public static void main(String[] args) {
    
          openApp();                
    }
    
  • 接下来,当openApp()被呼叫时,用户有三个菜单可供选择,通过输入相应的号码选择

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

public class MainPage {

公共类 MainPage {

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
                    }

    }
}
  • If User selects "friends" then the program calls a method from
    People Class called friend(People name)inMainPage class that prints out peopleobject's friends.
  • 如果用户选择了“朋友”,那么程序调用的方法
    人称为类friend(People name)MainPage类是打印出来的人对象的朋友。

My Attempt:

我的尝试:

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

The Error I get:

我得到的错误:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: people cannot be resolved

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

Problem is I don't want to extend People Class in MainPage and inherit all it's methods, yet I still want to call an Object method from People Class to print peopleobject's friends.

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

Note: just in case anyone would want to look at the friend(People people)method that is located in the People class:

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

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

采纳答案by christopher

Excellent question format.

优秀的问题格式。

You can declare an Objectof type People, and use that.

您可以声明一个Objectof type People,然后使用它。

Example

例子

public class MainPage
{
    People people = new People();

    // .. Some code.

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

Explanation

解释

Your friendmethod is an instance method. This means that in order to access it, you need to have an instance of the object created. This is done with the newkeyword. Secondly, unless Peopleis some form of utility class, then your friendmethod should probably read more like:

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

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

And for the sake of good code design, remember that your MainPageclass is outputting to the user, so you should returnthe value rather than print it. Secondly, you should conform to good naming standards, and in Javawe use the getprefix when getting a class member.

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

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

and in the MainPageclass, you should print this.

MainPage课堂上,你应该打印这个。

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