Home > Software engineering >  No enclosing instance of type savings is accessible in java
No enclosing instance of type savings is accessible in java

Time:04-08

im just getting message like "No enclosing instance of type savings is accessible." starting in line 17. I don't know what kind of instance that the IDE means. I'm learning java for 2 weeks now.

public class savings {
class MyInfo{
    String name;
    int balance;
}
class MyParent{
    String name;
    int balance;
}
class Mysister{
    String name;
    int balance;
}
public class Mainsimulationsavings {
public static void main(String[] args) {
    
    MyInfo me = new MyInfo();
    me.name ="gaga";
    me.balance =1000000;
    
    MyParent parent = new MyParent();
    parent.name ="Abdul";
    parent.balance =20000000;
    
    Mysister sis = new Mysister();
    sis.name ="Ifdah";
    sis.balance =500000 ;
    
    System.out.printf("|%-5s|%-10s|%-10s|%-10s|\n", "No", "No.ID", "balance", "name");
    System.out.printf("|%-5s|%-10s|%-10s|%-10s|\n", "--", "----", "-----", "----");
    System.out.printf("|%-5s|%-10s|%-10s|%-10s|\n", "1", "12345", "Rp." me.balance,me.name);
    System.out.printf("|%-5s|%-10s|%-10s|%-10s|\n", "2", "54321", "Rp." parent.balance,parent.name);
    System.out.printf("|%-5s|%-10s|%-10s|%-10s|\n", "3", "67890", "Rp." sis.balance,sis.name);
}
}

}

CodePudding user response:

Sticking classes in classes makes 'instance classes' which you don't want, usually. They have an extra invisible field of their outer type: You can't make new instances of e.g. Mysister here without also having an instance of savings available, which you don't. This is all very confusing so you never want to do this until you're much more advanced in java (and even then, I generally avoid it, saving a few characters at the cost of confusing code is rarely a good tradeoff).

Either don't stick classes in classes, or remember to always mark classes-in-classes as static. Such as static class MyParent {.

CodePudding user response:

The Answer by rzwitserloot is correct.

  • Related