How to call an object method from another class without creating a subclass class and / or inheritance?

I am learning basic code at a very beginner level. Now I'm finally starting to pamper, actually writing simple programs, and really stuck.

  • I am writing a simple program consisting of two classes; People, Homepage.

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

    public static void main(String[] args) {
    
          openApp();                
    }
    
  • Then, when called up openApp(), the user has three menus that need to be selected to go to the selected one by entering the corresponding number

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

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
                    }

    }
}
  • "",
    , friend(People name) MainPage, .

:

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

, :

"main" java.lang.Error: :      .

, People MainPage , Object People -.

: - friend(People people), People:

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

.

Object People .

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());
}
+1

All Articles