1

Edit: Sorry for my previous question, the final keyword will confusing you, It's not appropriate. And sorry for my poor English too.

-----Question------

Assume I have a model class without any constructor, because I need to initialize it within many different logic. But i have a notnull keyword.

public class Model {
    public notnull String name;
    public notnull String address;
    public notnull int age;
}

And I need to use it in different place but keep checking if all notnull fields were initialized in compile time

Model m = new Model();
m.name = "Hello";
m.age = 15;
// syntax error, you should set Model.address

Or

Model m1 = new Model();
m1.address = "World";
m1.age = 20;
// syntax error, you should set Model.name

How can I achieve that in java? Thx.

G.Bob
  • 101
  • 7
  • 2
    I'm confused. If they're final, you *have to* initialize them all in the constructor. – Andy Turner May 03 '17 at 05:49
  • 1
    you need to initialize them either when you declare them as `final String a = "A"`, in EACH constructor as `a = "A"` or within an instance initializer block as `{ a = "A" }`, otherwise you get a compile time error. The way you do currently have it set up the `final` wouldn´t make sense as you are not in need to initialize them which would contradict what the `final` is there for. – SomeJavaGuy May 03 '17 at 05:49
  • 1
    and "But I have a new keyword say notnull" lol.. –  May 03 '17 at 05:55
  • For the edit: that´s java not an sql table. there is no `notNull` or something similar in java. The most similar you can have is the `final`, which dooms you to initialize, where `null` isn´t forbidden... – SomeJavaGuy May 03 '17 at 05:57
  • @RC. The keyword *final* will make others teaching me java basic gramer. And that's not i'm asking ;-P – G.Bob May 03 '17 at 05:58
  • Now you changed your question from `final` to `not null`. This breaks previously given answers ... and your title still refer to final fields – Harmlezz May 03 '17 at 06:00
  • I think maybe you want a constructor with three parameters? `public Model(String name, String address, int age) { ... }` and initialize your fields from the parameters. I don't know, it's really hard to tell what you want. – ajb May 03 '17 at 06:03
  • @Harmlezz Sorry for confusing you. – G.Bob May 03 '17 at 06:30

5 Answers5

2

assume I have a model class without any constractor

This is not possible. Every class has a constructor. If you do not define one you end up with the default constructor. In your case:

public Model() {
    super();
}

checking if all final field were initialized

First, final fields must be initialized, otherwise the compiler will not compile. Hence you have to have to initialize final fields either:

  • in the constructor
  • when declaring the final field

Constructor Initialization

public final String name;
public final int age;

public Model() {
    this.name = "Hello";
    this.age = 13;
}

Declaration Initialization

public final String name = "Hello";
public final int age = 13;

public Model() {
    super();
}
Harmlezz
  • 7,972
  • 27
  • 35
1

You can achieve what you seems to want with something like this:

public class Model {
    private final String name;
    private final String address;
    private final int age;

    public Model(final String name, final String address, final int age) {
        if (name == null) {
            throw new IllegalArgumentException("please provide a name");
        }
        if (address == null) {
            throw new IllegalArgumentException("please provide an address");
        }
        this.name = name;
        this.address = address;
        this.age = age;
    }

    // getters
}

Usage:

new Model("World", "Some address", 20) // OK
new Model("World", null, 20) // Exception because null address.
0

You should look at the Builder Pattern. There are number of articles that you can find on the internet on how to use it. This is one example https://jlordiales.me/2012/12/13/the-builder-pattern-in-practice/. Using the Builder pattern you can validate if certain fields are set or not and throw exception if there are not.

tabiul
  • 607
  • 3
  • 8
  • 17
  • This is probably not an appropriate answer for someone who's still learning the basics of Java. – ajb May 03 '17 at 06:01
  • @ajb Actually I have such like JSON parser, HTTP Server, and many other tools built by myself with pure java. I mean it's not a basics question I think ;-P – G.Bob May 03 '17 at 06:08
  • @tabiul Thanks for your answer, I'm expecting more grammar level solution (check in compile time). Your answer is actually a Factory Design Pattern, means I should write another Class and It won't check in compile time. – G.Bob May 03 '17 at 06:13
  • ah ok, so you want to have some sort of new keyword `notnull`. Hmm, I maybe wrong but I think what you want is not possible in Java. Maybe you should use Scala :) as over there there is `Case Class` and you can use `val` and `var` – tabiul May 03 '17 at 06:16
  • 1
    @G.Bob not possible with keywords but you can use annotations. Not sure what IDE you are using but Intellij IDEA has built in `@NotNull` and `@Nullable` annotations also you can built your own annotations and annotation processors for other IDEs. http://stackoverflow.com/a/2386013/3133545 – Onur May 03 '17 at 07:44
  • @G.Bob My apologies. It's hard to tell sometimes. – ajb May 03 '17 at 13:08
  • @Onur Thanks, your answer is quite helpful for this question. – G.Bob May 04 '17 at 01:37
0

If only final : You can either instantiate them where you declare or instantiate inside the constructor.

If final + static: You MUST instantiate them where you declared.

So since they are not static you need to instantiate where you specified them or in the constructor.

Juliyanage Silva
  • 2,529
  • 1
  • 21
  • 33
0

Assume I have a model class without any constructor because I need to initialize it within many different logic. But I have a notnull keyword.

You need to note that even if you don't write any constructor, the compiler will provide a default no-argument constructor which will initialize all fields in the object to the default values automatically (i.e., String types to null and int types to zero values, etc..)


The class constructor is a right place to validate all mandatory fields are provided or not, so create your own constructor to check all mandatory fields are passed in during the object creation:

public class Model {
    private String name;
    private String address;
    private int age;

    public Model(String name, String address, int age) {
         if(name == null) { 
               throw new IllegalArgumentException(" Name is mandatory ");
         } 
         if(address == null) { 
               throw new IllegalArgumentException(" Address is mandatory ");
         }
         if(age < 0) { 
               throw new IllegalArgumentException(" Age is Invalid ");
         }
         this.name = name;
         this.address = address;
         this.age = age;
    }
   //Add getters and setters
}

Also, encapsulate the data of your Model class by marking your fields private (shown above).

Vasu
  • 21,832
  • 11
  • 51
  • 67