skip to Main Content

In the context of the following code:

Package a;
public class c {
    // ...
}

Package d;
public class a {
    public class c {
        // ...
    }
}

When I use ‘a.c’ to declare and instantiate an object

a.c my_var = new a.c()

Android Studio is recognizing the class ‘c’ from package ‘d’. However, I intend to access the class ‘c’ from package ‘a’. How can I achieve this without needing to change the package names or class names?

2

Answers


  1. You can achieve this by importing the class c from the package d into the package a. To do this, add the following import statement to the top of the class file in the package a

    import d.c;

    Login or Signup to reply.
  2. Continuing from the comment, let’s consider a real world scenario (using a, c, d… can be tough and misleading):

    
    package com.example.animals; // com/example/animals/Lion.java
    public class Lion {
    }
    
    
    package com.example.zoo; // com/example/zoo/Zoo.java
    public class Zoo {
        public class Lion {
        }
    }
    

    If you want to create an instance of the Lion class from com;example.animals and there is a Lion class in com.example.zoo package, you can do something like:

    
    com.example.zoo.Zoo.Lion zooLion = new com.example.zoo.Zoo().new Lion(); // This refers to the inner class Lion of class Zoo in package com.example.zoo
    
    // To refer to the class Lion in package com.example.animals, use the fully qualified name
    com.example.animals.Lion animalsLion = new com.example.animals.Lion();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search