2

What I have is two package emp and p5. I have one file consisting two classes one of them is public and another is default.

package emp;

public class Employee{

 public void display(){
     System.out.println("from DebarredEmply");
 }

}

class DebarredEmployee{

   public void display(){
        System.out.println("from DebarredEmply");
    } 

}

what I want to is create the object of DebarredEmployee in class lying in another package.

package p5;
import emp.DebarredEmployee;

class Test{
   public static void main(String[] args){
      DebarredEmployee dEmp = new DebarredEmployee();
      dEmp.display();
   }

}

I have tried above approach but it is giving me the error

error: DebarredEmployee is not public in emp; cannot be accessed from outside package

So how can I create the object of the class I want. ps:
I know defaults are not accessible outside the package and it will work if I make the class public and move it another file, I want to do that without making new file and keeping the access modifier as default one. –sorry for some sloppy naming conventions.

Govinda Sakhare
  • 5,009
  • 6
  • 33
  • 74

2 Answers2

1

You can put your DebarredEmployee class into Employee class as a static inner class. Like this:

public class Employee{

    public void display(){
        System.out.println("from DebarredEmply");
    }

    public static class DebarredEmployee{

        public void display(){
            System.out.println("from DebarredEmply");
        }

    }
}

And in your p5 package, you can use import static:

import static emp.Employee.DebarredEmployee;

class Test{
    public static void main(String[] args){
        DebarredEmployee dEmp = new DebarredEmployee();
        dEmp.display();
    }
}
Nier
  • 638
  • 7
  • 15
-1

Move the DebarredEmployee dEmp; variable decoration outside the main. If you don't want dEmp to be static you can make a new method that uses the dEmp and have the main method call it. Edit: This works because public variables can't be created inside methods

weeryan17
  • 11
  • 7