0

this is my code..but I'm encountering an error of null pointer exception whenever I try to access private variables of "Category" class to "Product" class in the applyCoupon() method...

//main class

public class basicjava{

        public static void main(String args[]){
            Product product=new Product();
            Category category=new Category();
            category.setCategoryName("book");
            product.applyCoupon();
    }

    }

//second class

 public class Product {
        private Category category;
        Product(){

        }

        public Category getCategory() {
            return category;
        }

        public void setCategory(Category category) {
            this.category = category;
        }

        public void applyCoupon(){
            if (category.getCategoryName()=="book") {
                System.out.println("book");
            }
            else {
                System.out.println("page");
            }
        }

    }

//third class

public class Category {
    private String categoryName;
    Category(){

    }

    public String getCategoryName() {
        return categoryName;
    }

    public void setCategoryName(String categoryName) {
        this.categoryName = categoryName;
    }
}
upog
  • 4,965
  • 8
  • 42
  • 81
  • category was not initialized in product. you can initialize the variables and objects through constructor before using them – upog Apr 19 '20 at 07:36

3 Answers3

0

This is because you don't initialize the internal category in your Product constructor. Java's default initialization for Objects is null, which is why you get a NullPointer Exception when trying to call a method from this instance.

Cerenia
  • 147
  • 7
0

Because you are doing this

Product product = new Product();

and inside your constructor thats being called

Product() {

}

you are not initializing the object yourself. No instance is created when your constructor is called.

And since no instance is created when you are trying to access an instance method you get a NullPointerException.

Please also look into what a NullPointerException here.

Abdullah Khan
  • 12,010
  • 6
  • 65
  • 78
0

you have to initialize the Non-Primitive Data Types in constructor or through set methods before using them

public static void main(String args[]) {
    Product product = new Product();
    Category category = new Category(); 
    category.setCategoryName("book");
    product.setCategory(category);
    product.applyCoupon();
}
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
upog
  • 4,965
  • 8
  • 42
  • 81