user3289740
user3289740

Reputation: 351

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

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.

public class 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
                    }

    }
}

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

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 people object's friends.

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

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

Upvotes: 3

Views: 31066

Answers (1)

christopher
christopher

Reputation: 27356

Excellent question format.

You can declare an Object of type People, and use that.

Example

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

    // .. Some code.

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

Explanation

Your friend method 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 new keyword. Secondly, unless People is some form of utility class, then your friend method should probably read more like:

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

And for the sake of good code design, remember that your MainPage class is outputting to the user, so you should return the value rather than print it. Secondly, you should conform to good naming standards, and in Java we use the get prefix when getting a class member.

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

and in the MainPage class, you should print this.

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

Upvotes: 1

Related Questions