0

I was learning about packages in java. I created 2 packages, "main" and "main2". Both the packages have a class which has the same name. And in both the classes I also have a method with same name. Currently I am working with the package "main".

See the below code:

"main" package

package main;
import main2.*;

public class learning {

    public static void main(String args[]) {
        okay obj = new okay();
    }
}

class okay{
    void hello(){
        System.out.println("Hello");
    }
} 

"main2" package

package main2;

public class okay{

    public static void main(String args[]) {
    
    }
    public void hello() {
        System.out.println("Hello1");
     }
}

Here I am currently working with package "main". Here I am also importing the package "main2". Now I want to create an object of "okay" class of the "main2" package. Since the "main" package has already a class called okay and the same method name It is not calling the hello method of package main2.

package main;
import main2.*;

public class learning {

    public static void main(String args[]) {
        okay obj = new okay();
    
        // Creating an object of okay class in package main1.
        okay obj1 = new okay();
    
        // calling the hello method of okay class in package main1.
        obj1.hello();
    }
}

class okay{
    void hello(){
        System.out.println("Hello");
    }
 }

But it is only calling the hello method of package main. How do I call the hello method of package main1. Is there any methods for it. Or is it impossible to call the method of same name. Pls reply. I tried my best to explain the question.

  • Use the full qualified name with package.class for example new main.okay() – TomStroemer Jul 23 '22 at 14:44
  • Does this answer your question? [java.util.Stack collision with Own stack class in java](https://stackoverflow.com/questions/25457814/java-util-stack-collision-with-own-stack-class-in-java) – plplmax Jul 23 '22 at 14:45
  • 1
    strongly advised to: 1) stick with the usual naming convention for Java (e.g class names start with Uppercase; 2) do not use the same name for different classes (unless for learning/testing) – user16320675 Jul 23 '22 at 15:09
  • check this one https://stackoverflow.com/questions/73090789/two-classes-with-same-name-and-same-attibute-in-java/73090819#73090819 –  Jul 23 '22 at 15:22

1 Answers1

0

Use the fully qualified name of the class you wish to refer to.

public static void main(String args[]) {
    okay obj = new okay();

    main2.okay obj1 = new main2.okay();

    obj1.hello();
}
Geoff
  • 165
  • 11