Search code examples
javainheritanceaccessormutators

Mutator and Accessor(Using Inheritance)


I want my program to input a private variable from another class.

I want to use the mutator and accessor.

It keeps erroring NullPointerException. What's the problem in my code?

public abstract class Inputs {
private String val;
private String typ;
public abstract void setVal(String val);
public abstract void setTyp(String typ);
public abstract String getVal();
public abstract String getTyp();
}

public DeckOfCards extends Inputs{
String val;
String typ;
static DeckOfCards kerds = new DeckOfCards();
    public void setVal(String val){
        this.val = val;
    }

    public void setTyp(String typ){
        this.typ = typ;
    }

    public String getVal(){
        return this.val;
    }

    public String getTyp(){
        return this.typ;
    }
    public static void main(String args[]){
       System.out.print("Value: ");
       kerds.setVal(kerds.val);
       if(kerds.val.equals("A"){
          System.out.print("Type: ");
          kerds.setTyp(kerds.typ);
       }
    }
}

Solution

  • Here is your problem kerds.setVal(kerds.val); kerds is not created yet when main runs.

    • You need to initialize the instance of DeckOfCards before using it.
    • Only attempt to retrieve values after they are set. Else the attempt to retrieve a value that isn't yet set will throw a NullPointerException (Just as Rehman has pointed out)

    Here is an example of proper usage:

         public static void main(String args[]){
            DeckOfCards kerds = new DeckOfCards();
            kerds.setVal("A");
            kerds.setTyp("TYPE_A");
    
            System.out.println("Displaying values of kerds");
            System.out.println("kerds value : " + kerds.getVal());
            System.out.println("kerds type : " + kerds.getTyp());
            }