0

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);
       }
    }
}
Mariel
  • 169
  • 2
  • 5
  • 18

2 Answers2

1

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());
        }
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Clyde D'Cruz
  • 1,915
  • 1
  • 14
  • 36
0

kerds.setVal(kerds.val) is setting a null value. At that point value of kerds.val is not set yet . Basically your code doesnt make any sense. You are setting a property with a value of same property which is not set yet.

Rahman
  • 3,755
  • 3
  • 26
  • 43