2

I am new to java and I keep getting this error message:

No enclosing instance of type Managesalary is accessible. Must qualify the allocation with an enclosing instance of type Managesalary (e.g. x.new A() where x is an instance of Managesalary). on line *

public class Managesalary
{
    public static void main(String[] args)

    {
        System.out.println("MY SALARY REVIEW");
        System.out.println("================");


    *   Salary Jan= new Salary();
        Jan.Month= "JANUARY";
        Jan.HoursWorked= 12;
        Jan.PerHourRate= 10;
        Jan.TaxRate= 0.10;

        Jan.printSalaryDetails();

        Salary Month2= new Salary();
        Month2.Month= "FEBUARY";
        Month2.PerHourRate= 10;
        Month2.TaxRate= 0.10;
        Month2.printSalaryDetails();

    }

class Salary
    {
    String Month = "";
    int HoursWorked= 0;
    int PerHourRate= 0;
    double TaxRate= 0.10;
    int MonthlySalary= (HoursWorked*PerHourRate);

    public void printSalaryDetails(){
        System.out.println("MONTH OF = " +Month);
        System.out.println("PER HOUR RATE = " +PerHourRate);
        System.out.println("TAX RATE =   " +TaxRate);
        System.out.println("TOTAL MONTHLY INCOME = " +MonthlySalary);
        System.out.println("================");
    } 
    } 
}
Ry-
  • 218,210
  • 55
  • 464
  • 476
Jaz Bansal
  • 33
  • 1
  • 3
  • 1
    Possible duplicate of [Java - No enclosing instance of type Foo is accessible](http://stackoverflow.com/questions/9560600/java-no-enclosing-instance-of-type-foo-is-accessible) – Raedwald Mar 02 '16 at 22:41

5 Answers5

2

The error sais that you have to create a inner class by referencing an instance of the enclosing class.

ManageSalary mn = new Managesalary()
Salary salary =  mn.new Salary();
Averroes
  • 4,168
  • 6
  • 50
  • 63
2

Either copy your class Salary in a separate file name Salary.java and make it public, put it outside of you main class preferably above it, or declare it static.

Willem
  • 376
  • 2
  • 8
1

Inner classes need an existing reference to the outer class. Without an instance of Managesalary it won't be possible to instantiate Salary. You can achieve this by doing:

Managesalary mSalary = new Managesalary();
Salary Jan= mSalary.new Salary();
Fritz
  • 9,987
  • 4
  • 30
  • 49
0

You have defined the Salary class as an inner class of Managesalary (although your code indentation hides this a bit).

Thus, each instance of Salary must be bound to an instance of Managesalary.

In your main method, create an instance of Managesalary (e.g. ManageSalary ms = new ManageSalary()) and initialize your inner class object as ms.new Salary().

sebastian_oe
  • 7,186
  • 2
  • 18
  • 20
0

Make your Salary class as static

static class Salary{
    // rest of the code
}
MinA
  • 405
  • 4
  • 9