I have an enum like
public enum Field {
A, B, C, D, E ....;
private Field(){
}
}
I have a class Panel that takes Field array to initialize the fields:
public class Panel {
TextBox A;
TextBox B;
TextBox C;
TextBox D;
TextBox E;
...
public Panel(Field[] fields){
this.fields = fields;
init();
}
public void initA(){}
public void initB(){}
public void initC(){}
public void initD(){}
public void initE(){}
}
My question is, how can I initialize the fields that given without writing many if statement?
I can't find any solution and I'm now initializing like this:
public void init(){
for(int i = 0 ; i < fields.length; i++){
if(fields[i] == Field.A){
initA();
} else if(fields[i] == Field.B){
initB();
} else if(fields[i] == Field.C){
initC();
} else if(fields[i] == Field.D){
initD();
} else if(fields[i] == Field.E){
initE();
} ....
}
}
Sounds like your design might need to be looked at. A few suggestions:
Add the init method to your enum. So
then you can iterate around the array
of your enums and call the init
method on it, so the enum knows how
to do its own initialization
create a Command object which does
the initialization and create a
Map of your enum as the key and
the Command as the value. Cycle
round the map running the Command
for each enum.
Use reflection - cost wise I wouldn't be too concerned for this, unless your system is after incredibly low latency
For the first bullet, you could change the TextBox to hold a Field type against it e.g.
TextBox A = new TextBox(Field.A);
TextBox B = new TextBox(Field.B);
So if TextBox knows it is A,B,C,D,E then you just need to loop around your Field[] and when it finds its mathing TextBox run the init code (which can be stored against the specific enum instance). Of course you will need to register all your TextBox instances in a data structure somewhere, as you seem very set against using the very widely used reflection API.
In essence there has to be a link between the Field and the TextBox. Java cannot read your mind and know this without you telling it. Well, at least until Google unveil their telepathy API (and that would probably only be for Go...). This can be done based on naming (reflection), hardcoded logic (ifs or switches) or based on state. For the latter this means associating the Field with the TextBox, as I have demonstrated with the Constructor example above.
From a design perspective I'd choose a combination of Factory pattern, Singleton pattern (enum based) and Command pattern. I see a set of commands where each command is specific for a given value. A factory (Singleton) is a common pattern to create such specialized instances. Even though it simply moves the if/switch chain into the factory (but factories are allowed use conditional checks in order to create the instances..).
// the init command
public interface PanelInitializer {
public init(Panel p);
}
// the factory
public enum PanelInitializerFactory {
INSTANCE;
public PanelInitializer create(Field field) {
switch (field) {
case A: return new TypeAInitializer();
case B: return new TypeBInitializer();
case C: return new TypeCInitializer();
//..
}
}
}
I don't think that we can get rid of all conditional checks without using naming conventions and reflection/instantiation or without introducing the constraint, that all initializers share the same code.
Here's a snippet featuring adding the init method to the enum. In each Field's init method you can call one of your different initX() methods. Making the init method abstract gets the compiler to remind you to define your init method for the enum value.
enum Field
{
A{public void init(){initA();}},
B{public void init(){initB();}},
C{public void init(){initC();}},
public abstract void init();
}
You can, as #planetjones mentioned, add an init() method to your enum class. The init method should return a reference to the initialised TextBox of its (enum) type. If you need to pass data to the initialisor you can pass this so that it can retrieve any information it needs.
To get around the problem of finding the variable to assign to, you can either declare an array of TextBoxes
public void init(){
for(int i = 0 ; i < fields.length; i++){
F[i] = fields[i].init(this);
}
}
or assign them after you initialised a temporary array.
public void init(){
TextBox F[5];
for(int i = 0 ; i < fields.length; i++){
F[i] = fields[i].init(this);
}
A = F[0];
B = F[1];
C = F[2];
D = F[3];
E = F[4];
}
Of course you should declare constants instead of using magic numbers.
You could use java reflection to loop through your enum, but you really should look into some way to consolidate all your initN() methods.
Why you current implementation is bad? Only because it looks "ugly"? You can use switch instead of bunch of if:
public void init(){
for(int i = 0 ; i < fields.length; i++){
switch(fields(i)){
case A:
initA();
break
case B:
...
}
}
}
Maybe logic in initA, initB... is very similar? If you have 20 different enums, and 20 different init to run, not much space for improvement...
You could do it, for example, by moving initialization logic to the enum. Have there a method initialize that takes a TextBox as the parameter and initializes it.
BTW you would be better having the TextBox variables in an array.
EDIT
Another option is, what I often is I use an enum as a sort of archetype storage. There I have a method returning an object which matches a certain enum type.
If you do not want to have initialization in enum you could move it to objects you are going to return. There for each particular object you will have a separate initialization.
I am afraid that you are trying to chase the dragon with this one.
Look at it this way. Since the problem of yours is 'conditional', i.e. you have to do a different initialization depending on enum type of a Field, thus at some point you will have to use ifs or switch statement.
Believe there is no magic way around it, how the program should know what you want to do? Even using reflection you will use ifs, etc. to initialize it accordingly.
Your approach is not at all bad if the init methods associated with each TextBox is very different, and the list of Fields is small. Also, if you typically instantiate only one of these Panel instances, the other approaches can actually hurt more than help.
Having said that, consider using a java.util.EnumMap. After that, you have three choices:
register the TextBoxes in some other array as well,
invoke the initA, ... using reflection or
invoke them using some functor construct.
The best choice depends on use case.
Start with this example:
import java.util.HashMap;
import java.util.Map;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class FooPanelMain {
public static void main(String[] args) {
FooPanel panel = new FooPanel();
JFrame frame = new JFrame();
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
class FooPanel extends JPanel {
// fields are dynamically created, so we put them into a map
private Map<PanelField, JLabel> fields = new HashMap<PanelField, JLabel>();
// enum to configure the fields
private enum PanelField {
FIRST("first text"),
SECOND("second text"),
LAST("last text");
private String text;
private PanelField(String text) {
this.text = text;
}
public String getLabelName() {
return text;
}
}
// constructor uses the enum configuration to create the fields
public FooPanel() {
for (PanelField fooPanelField : PanelField.values()) {
createLabel(fooPanelField);
}
}
private void createLabel(PanelField field) {
JLabel label = new JLabel(field.getLabelName());
this.add(label);
fields.put(field, label);
}
}
This example can be easily turned into a abstract solution by defining an interface for PanelField, that is implemented by enums. FooPanel can be used as a base class for Panels.
best u move the init into the enum, just like:
public enum Example{
value1(1),
value2(2),
value3(66);
private final int internalValue;
Example(int value){
this.internalValue = value;
}
public int getInternalValue(){
return this.internalValue;
}
}
Although this is really simple example, you can add any code to the constructor later on and have more complex decisions based on the actual object itself.
Related
I'm learning Java and I'm fairly new to this. Here is my problem with some pseudocode:
public void objectCaller(int objectNumber) {
switch(objectnumber) {
case 1:
object1.setFill(color.RED);
break:
case 2:
object2.setFill(color.RED);
break;
.
.and so on
}
}
Is there a way to replace it in a way with something like that?
public void objectCaller(int objectNumber) {
(object + objectnumber).setFill(color.RED);
}
It is not a concrete problem. I was just thinking about if it is possible to assemble the object names.
There are three approaches you can use to solve the problem (Reflection is the last option I would recommend) :
Option 1 : Employ the Strategy pattern
If method1 and method2 are not objects of classes that are related. Employ the Strategy pattern as follows :
public interface Filler {
public void fill(Color color);
}
Create two classes that fill colors differently :
public class FloodFill implements Filler {
public void fill(Color color) {
//fill using flood fill algorithm
}
}
public class QuickFill implements Filler {
public void fill(Color color) {
//fill using quick fill algorithm
}
}
You can then use the Map approach explained below :
Option 2 : Use a HashMap
Assuming that method1 and method2 are related either through a common parent or through a parent child relationship, create a HashMap and prepopulate it with method1 and method2 objects :
Map<String,Filler> methods = new HashMap<>();
FloodFill method1 = new FloodFill();
QuickFill method2 = new QuickFill();
map.put("FloodFill",method1);
map.put("QuickFill",method2);
You can then change the methodCaller method to :
public void methodCaller(String method,Color color) {
methods.get(method).fill(color);
}
The client code can then look like this :
methodCaller("FloodFill",Color.RED);
methodCaller("QuickFill",Color.GREEN);
Using a HashMap instead of a basic array or a List allows you to associate meaningful names to your method calls. The HashMap is kind of a Factory for objects. The String constants used as the key for the Map can be defined as enum instead.
Option 3 : Use reflection :
This is not something I would recommend for this particular case but if you have to, take a look at this answer on how to achieve this trough reflection.
You could do that by reflection, but for this case is clearly overkill.
What about this approach?: Store your objects in an array (or a List) and then use the index to access the required one.
Note that I'm assuming that all the objects are of the same class or are least they have a parent-child class relationship, as #ChetanKinger pointed in the comment below.
public void methodCaller(int methodNumber) {
myArrayOfObjects[methodNumber].setFill(color.RED);
}
PS: In fact, you are trying to compose "object" names, not methods names. In that case you would really need to use the Reflection API
I tried googling and searching for this question but somehow couldn't find anything relevant about it. I'm wondering if there is a bbest-practise guide on when to use attributes in a class and when not, but rather use parameters to the single methods.
Many cases are clear to me, e.g.
public class Dog
{
private name;
public setName(...) {....}
}
But sometimes it's not clear to me what's better to use.
E.g. the following, either use:
public class calculation
XYZ bla;
public calculation(XYZ something)
{
this.bla = something;
}
public void calc1()
{
// some calculations with this.bla
}
public void calc1()
{
// some more calculations with this.bla
}
public XYZ getBla()
{
return this.bla;
}
}
or maybe do:
public class calculation
public calculation() {}
public static XYZ calc1(XYZ bla) // maybe static, if not dependant on other attributes/instance-variables etc
{
// some calculations with bla
return bla;
}
public static XYZ calc1() // maybe static, if not dependant on other attributes/instance-variables etc
{
// some more calculations with bla
return bla;
}
}
I mean you can argue for both cases. I see advantages and maybe disadvantages for both different styles, but somehow I prefer the second one as far as long as there are not too many arguments/parameters needed. Sure, if I need many many more attributes etc., then the first one will be better, simpler etc. because I dont need to pass so many parameters to the method...
Just a question of personal style?
Or how to decide for one approach?
Thanks
EDIT: A better example: I'm curently doing much image processing and the question would be wether to store the image internally in the state of the object or not. I'm currently NOT doing it because I'm using static methods, and psasing the image itself I to each method:
public class ImageProcessing
{
/**
*
*/
public static Mat cannyEdges(Mat I, int low, int high)
{
// ...
return I;
}
public static Mat cannyEdges(Mat I)
{
return ImageProcessing.cannyEdges(I, ContourDetection.CANNY_LOWTHRES, ContourDetection.CANNY_HIGHTHRES);
}
/**
*
*/
public static Mat getHoughLines(Mat Edges, ...some_conf_vars...)
{
// ...
return I;
}
}
and then I'm calling it from the outside like this e.g.:
// here: read image to I...
Mat edges = ImageProcessing.cannyEdges(I, 20, 100);
Mat lines = ImageProcessing.getHoughLines(I);
// draw lines...
question is: Does I belong to the state of the object? Would it make sense to convert to non-static and then use for example:
// here: read image to I...
ImageProcessing IP = new ImageProcessing(I);
IP.cannyEdges(20, 100); // CHANGE OF cannyEdges: Also save `edges` internally as property!?
IP.calcHoughLines(); // also save the lines internally maybe?
Mat lines = IP.getLines();
// draw lines...
is this nicer?
The question arising is then again: Should I for example store the result of getHoughLines() (i.e. the lines) internally or should I directly return it to the caller!?
I can use some examples:
public class Multiplier {
private int number;
public Multiplier(int number) {
this.number = number;
}
public int multiply(int other) {
return number * other;
}
}
This class could be instantiated like:
Multiplier multiplyByTwo = new Multiplier(2);
I could use it to multiply many elements on a list by 2.
But I could need to multiply pairs of numbers. So the following class could be what I neeed:
public class Multiplier {
public static int multiply(int number, int other) {
return number * other;
}
}
I could make it static since no state is needed.
This example could be used like this on a list:
for (int x:listOfInts) {
print(Multiplier.multiply(x * 2));
}
But probably in this specific case the 1st example was nicer.
for (int x:listOfInts) {
print(multiplyByTwo(x));
}
or even nicer used with a Java 8 ''map''
If I need to get the elements of the multiplication and the result at many points in my code i could do.
class Multiplier {
private int x;
private int y;
public int multiply() {
return x * y;
}
// getters and setters for x and y
}
In this last case I may consider not adding setters and pass x, y in the constructor.
Every structure could be used in some specific cases.
It's not entirely a question of personal style. But nevertheless, I assume that this topic might be slightly controversial (opinion-based) and thus not perfectly suited for a Q/A-site.
However, the obvious question is: Does an object of the respective class really carry a state? That is, is there any benefit in having the state represented by an instance? If the sole purpose of the instance is to be an accumulator of variables that are modified with a sequence of set... calls and a final call to an execute() method, then there is usually no real justification for such an instance - except for avoiding to have a static method with "many" parameters.
I think that the advantages of static methods outweigh most of the potential clumsiness of calling a method with "many" parameters. One of the most important ones is probably that the approach with static methods doesn't increase the state space. Every field is another dimension in the state space, and documenting state space properly can be hard. Static methods enforce a more "functional" programming style: They don't have any side-effects, and thus, are thread-safe (which is becoming increasingly important).
(Note: All this refers to static methods that are not related to any static state - that should be avoided anyhow. And of course, this refers to methods that are not involved in or aiming at anything related to polymorphism).
And after all, one can easily call any static method from anywhere - even from within an instance method, and pass in some fields as parameters. The opposite is not so easy: When you want to call a method that depends on many instance fields, it can be a hassle when you first have to create an object and set the fields appropriately (still not knowing whether it is in a valid state to call the method). I also see the default methods of Java 8 as a nice application case where static utility methods come in handy: The default method may easily delegate to the utility method, because no state is involved.
There are a few reasons I'd go with the first option, i.e. an object with state over static functions, particularly for complex calculations but also for simpler ones.
Objects work better for the command pattern.
Objects work better for the strategy pattern.
Static methods can turn unit tests into a nightmare.
Static is an anti-pattern in OOP because it breaks polymorphism, with the side-effect that related techniques will break with it, e.g. open/closed, mocking, proxies, etc.
That's my 2c at least.
The weird part of your first example is that those calcX methods don't say anything about idempotency, so it's unclear what this.bla is when it's being manipulated. For complex computations with optional settings, an alternative is to construct an immutable object using a builder pattern, and then offer calcX methods that return the result based on fixed object state and parameters. But the applicability of that really depends on the use case, so YMMV.
Update: With your new code, a more OOP approach would be to decorate Mat. Favouring delegation over inheritance, you'd get something like
public class MyMat
{
private Mat i;
public MyMat(Mat i) {
this.i = i;
}
public Mat getBackingMat() {
return this.i;
}
public MyMat cannyEdges(int low, int high)
{
// ...
return new MyMat(I); // lets you chain operations
}
public MyMat cannyEdges()
{
return new MyMat(ImageProcessing.cannyEdges(I, ContourDetection.CANNY_LOWTHRES, ContourDetection.CANNY_HIGHTHRES));
}
public MyMat getHoughLines(...some_conf_vars...)
{
// ...
}
}
MyMat myMat = new MyMat(I);
lines = myMat.cannyEdges(20, 100).calcHoughLines();
This is just a guess, cause I have no idea what those things mean. :)
When not to use static:
If the result that will be returned is dependent on other variables (state) that make up your "calculation" class then static cannot be used.
However, if you are simply doing calculations on a variable, as the example implies, static is probably the way to go as it requires less code (For example to perform calc1 and then calc2 on a variable by the first method you would have to do:
calculation calc = new calculation(x)
calc.calc1();
calc.calc2();
XYZ y = calc.getBla();
while with the second example you could do
static import ...calculation.*;
...
XYZ y = calc2(calc1(x));
Ok my problem isnt really a serious one, im just trying to find a clever way of access/modification of class member variables. Here is the code:
public class Storage{
private int cookies= 0;
private int rolls= 0;
private int candies= 0;
private int lolipops= 0;
private int iceCreams= 0;
public void addCookies(int howMuch){ //this is the dirty way of creating method for
this.cookies = cookies+howMuch; //every member variable
}
public void addValue(String stat, int howMuch){ //i would like to do it only
//by passing the name
//of variable and then cast it as integer
//so that it would relate to my class members
int value = this.(Integer.parseInt(stat)); // <- YES i know its ridiculous
//im just trying to explain what is my aim
value = value + howMuch;
this.(Integer.parseInt(stat)) = value;
}
}
Generally i would like to access a field by passing its name to a method, read value of that member, add to it some value, and then store it. Yes i know that it easily can be done with separate methods, or even with one by using some arraylist and comparisons of member names with parameter passed to method. But i would like to do it "fast" without redundant code writing.
Now i have like 5 members, but what about 15000? My aim is to simplify the whole processing and code writing. So generally is it possible to do such redundant code writing bypass? Since i know that i will always pass appropriate name to method... Unless the rule of thumb is to create method for each variable?
Normally you would use a collection like a Map.
public class Storage{
private final Map<String, Integer> inventory = ...
public void addCount(String key, int count) {
Integer i = inventory.get(key);
if (i == null) i = 0;
inventory.put(key, i + count);
}
I guess that by using reflection you can iterate through the fields/methods of your object and do your computation.
For one specific field:
Field member = myObject.getClass().getField(fieldName);
// If you know the class: Field member = MyClass.class.getField(fieldName);
System.out.println(member.getInt(myObject)); // Get the value
member.setInt(myObject, 4); // Set the value
If you want to something for all the public members:
for(Field member: myObject.getClass().getFields())
// Or you can do: for(Field member: myClass.class.getFields())
{
member.getInt(myObject)); // Get the value
member.setInt(myObject, 4); // Set the value
}
Basically, what you do is that you find the Field object that represents the members of you object, then you can manipulate it.
Most IDEs will generate setters and getters for you. This will do what you want with no bother or effort. If this is insufficient, write a method which uses reflection to set the values.
If you have a class with 15000 members, and by this I assume you mean variables private to a class, then you have other issues to resolve.
I would have a string that is parsed into an array, as shown here:
class Example extends ParentClass {
private String[] array;
public static Example parseString(String lineToParse) {
array = lineToParse.split("\");
}
public ObjectType1() { // arguments: String, String, String
}
public ObjectType2() { // arguments: String, String, String, double, double
}
}
What I'm wondering is could I do this?
if (array[0].equals("Test")) {
public ObjectType1()
}
Or is there a better way to do this?
I want to create various objects with different arguments each, and the first argument (array[0]) will be applicable to each object, so I was wondering if I could create objects within an if statement like this, or a switch (not sure if that would work either).
I believe a factory method would be useful for you, one that returns instances of classes according to the parameter received:
// ObjectType1, ObjectType2, ObjectType3 inherit from ObjectType
static ObjectType getInstance(String[] array) {
if (array[0].equals("Test"))
return new ObjectType1(array);
else if (array[0].equals("Test2"))
return new ObjectType2(array);
else
return new ObjectType3(array);
}
For the record, actually you can define a class inside a method, this is valid code in Java ... of course, that's hardly a good thing to do:
// ObjectType1, ObjectType2 inherit from ObjectType
public ObjectType example(String[] array) {
if (array[0].equals("Test")) {
class ObjectType1 {
ObjectType1(String[] array) {
}
}
return new ObjectType1(array);
}
else {
class ObjectType2 {
ObjectType2(String[] array) {
}
}
return new ObjectType2(array);
}
}
"Creating" an object means "instantiating it", with new:
ObjectType1 foo = new ObjectType1(...);
You can do that anywhere it's legal to instantiate a class, including in an if statement.
You cannot define classes in arbitrary locations, however.
If you just want to call a method (which should start with a lower-case letter if you want Java developers to understand what you're trying to do), you can call it from anywhere, including inside if statements.
This sounds like you may want to use a [static factory method][1].
[1]: http://en.m.wikipedia.org/wiki/Factory_method_pattern
I guess that you want to dynamically create objects based on a configuration file?
There are lots of ways to achieve this. One simple way is to use reflection to create the objects. Then you do not need any if/switch statements, and if you want to create a new type of object your code does not need to be changed.
Here are some examples for using reflection: Reflection API Code Samples
I am having some trouble understanding classes in Java.
Such as how do you declare "Inputter" in the helper class like this?
public class Helper
{
public void Helper(String z)
{
if(z.length() == 0)
{
System.out.println("You can't leave it blank!");
System.exit(1);
System.out.println("It's not working... ;(");
}
}
public void Inputter(int a)
{
// blah blah
}
}
Would you call it like this?
Helper x = new Inputter();
Please help, and NO this is NOT a homework question.
Thanks,
Smiling
EDIT: Would this be right:
public class Helper
{
public Helper(String z)
{
if(z.length() == 0)
{
System.out.println("You can't leave it blank!");
System.exit(1);
System.out.println("It's not working... ;(");
}
}
public void Inputter(int a)
{
// blah blah
}
}
and declared with:
Helper x = Helper();
And thanks everyone for giving me a warm welcome to StackOverflow! :D
Your problem is not with classes, it is with constructors and methods, and the difference between them.
Methods can have any name you like, they must declare a return type (possibly void), and they're called like this:
ReturnType r = methodName(param1, param2)
Constructors are used to create instances of classes (objects). They must have the same name as the class, they must not have a return type (not even void), and they're called like this:
MyClass m = new MyClass(param1, param2);
There are several problems in your code:
Helper has the correct name for a constructor, but because it declares a void return type, the compiler will treat it as a method.
Inputter doesn't even have the correct name for a constructor. To use it as a constructor with new, it would have to be part of a class called Inputter
Perhaps you should start out reading the introduction to OO part of the Java tutorial.
Inputter() that you have defined is a method or you can call it a behavior. You cannot create an instance for a behavior.
One more problem is that you cannot have return types on a constructor. Helper is the class name and the constructor is having a return type which is incorrect
Regarding your quesiton, if you want to call Inputter, you should do it something like the following.
Helper helper = new Helper("test");
helper.Inputter(100);
It is a good practice to start methods with smaller case letters.
The only object here is Helper. If you want to make a new helper, then you will instantiate it by saying
Helper X = new Helper("blah blah");
If you want to call Inputter then you just say
X.Inputter(1234);
Which will call the Inputter function for the specific instance X of Helper
You must create an instance of Helper Before you can use Inputter:
Helper x = new Helper("some string");
to use Inputter, try this:
//create a new helper
Helper x = new Helper("some string");
//use the Inputter method of the helper.
x.Inputter(1);
The thing to understand here is that Helper is the class, x is an instance of a class, and Inputter is a instance method (which is different from a static method) in the Helper class.
Inputter in your code is not a class. It is a method.
To make following statement correct:
Helper x = new Inputter();
you would need to create Inputter class that extends Helper class.
Inputter is not a class. It's a method of the Helper class. So you cannot instantiate it.
You can call it like this
String someString = "some string";
Helper x = new Helper(someString);
int someInt = 1;
x.Inputter(someInt);
The new keyword is reserved for instantiating (fancy word for saying "making new") classes. The way your class is made, when you make a new Helper, a function is run. That is the construct function, and is named like the class.
Once you instantiate a class, you gain access to the goodies within it (exception is a static method/attribute, where anyone can access it); all within the class that isn't private or protected.
Now, a short intro on OOP (Object Oriented Programming):
You have classes, which are basically blocks of functionality. Within these classes are two things: Methods and Attributes (many names for that, but that's what I call them.)
A Method is basically a good ol` function: It has an input and an output.
An attribute is really like any other variable.
Now, in Java and many other OO languages, there's a separation between the class declaration and class instances. A class declaration is basically the static coded class; exactly what you put in the code. A class instance is taking the class declaration and putting it into use: You can change and use the methods and attributes inside them.
So, if you want to call Inputter, you should do it like this:
Helper bob = new Helper('Bloop');
bob.Inputter(42);
What happened here? We made a new variable called bob which has a type of Helper. When constructing the new Helper, we also run the constructor. Looking at the constructor function, we pass a value to it (in this case, 'Bloop'), and the function is run normally, without us having to manually call it.
Now we want to use the Helper class' Inputter method. For that, we need to access an instance of the Helper class (in our case bob), by using bob. (notice the dot), and then calling it like any other function: Inputter(parameters). Gluing it together we get bob.Inputter(parameters)
This was a really rather lame explanation of Object orientation that didn't cover that much, but it should get you started. I recommend getting a book about Java or reading online tutorials.
First, start with the basics.
Classes best represent nouns. That means a Class is a model of (typically) a thing. Methods best represent verbs on those nouns. Drifting away from this ideal is sometimes necessary; however, the further you stay away from such an ideal, the harder it will be to understand what is going on. With a nod to the exceptions, since you're a beginner let us not get wrapped up in the exception but follow the rule.
public class Person {
private String name;
private int age;
public Person(String name) {
this.name = name;
this.age = -1;
}
public void setAge(int value) {
if (value < 0) {
throw new IllegalArgumentException("Age must be greater than zero");
}
this.age = value;
}
public int getAge() throws IllegalStateException {
if (age < 0) {
throw new IllegalStateException("Age was not set");
}
return this.age;
}
}
Read through the class above, and use its style for your beginning programs. When you find that its style is hindering you more than helping you, then you might have found a place where other techniques are needed.