Reputation: 527
I'm having three model class MyApp, Product and ProductDetails. I'm trying to set value in ProductDetails but I'm getting null pointer exception. Can someone please help me what I'm doing wrong here:
MyApp.java
public class MyApp {
private Product product;
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
}
Product.java
public class Product {
private ProductDetails details;
public ProductDetails getDetails() {
return details;
}
public void setDetails(ProductDetails details) {
this.details = details;
}
}
ProductDetails.java
public class ProductDetails {
private String productName;
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
}
Test.java
public class Test {
public static void main(String[] args) {
MyApp m = new MyApp();
m.getProduct().getDetails().setProductName("testProduct");
System.out.println("Name : " + m.getProduct().getDetails().getProductName());
}
}
I'm getting below exception: Exception in thread "main" java.lang.NullPointerExceptio at Test.main(Test.java:7)
Upvotes: 0
Views: 382
Reputation: 4833
You have to initialize product.details and details.productName before using it. For example:
m.getProduct().setDetails(new ProductDetails());
m.getProduct().getDetails().setProductName(...);
What about the Product in Variable m?
Upvotes: 2