Related
Hi all,
I would like to ask you for help to understand logic of this program specially some parts that I am probably stack in.
1.Method ranking(). It doesn´t accept any parametr but returns result from parametrs "won" and "tied". OK. But when we call this method like this
System.out.println(adelaideCrows.getName()+": result:
"+**adelaideCrows.ranking()**);
how the program knows values of "won" and "tied" for this adealideCrows team? I know that OOP is about passing objects respective references to objects. So does it work so that when we firstly call method adelaideCrows.matchResult(ohioFotlball, 1,0); then adelaideCrows is the reference to method matchResult passing there parametres in brackets and then they are stored in memory under reference of adelaideCrows? so when we next call the same method with another reference melbournSoccer.matchResult(newyorkSoccer,6,4); then parametres "won" and "tied" have their own values passed in brackets under reference melbournSoccer? So after calling method ranking() with reference e.g. adelaideCrows program knows that under this reference there are already stored values of parametres "won" and "tied" and method then returns correct values. Right?
2.And also here System.out.println(melbournSoccer.compareTo(newyorkSoccer)); Does the logic is the same? melbournSoccer reference is connected in method public int compareTo(Team<T> team) to this.ranking() but reference newyorkSoccer is connected to team.ranking()? So calling this.ranking() invokes values stored in memory of reference melbournSoccer and so on?
Thank A LOT.
Here is the code for Main class:
public class Main
{
public static void main(String[] args) {
SoccerPlayer soccerPlayer = new SoccerPlayer("joe");
BaseballPlayer baseballPlayer = new BaseballPlayer("pat");
FootballPlayer footballPlayer = new FootballPlayer("backham");
Team<FootballPlayer> adelaideCrows = new Team<>("Adelaide Crows
footbal");
Team<SoccerPlayer> melbournSoccer = new Team<>("Melbourn soccer");
Team<BaseballPlayer> jerseeBaseball = new Team<>("Jersee
Baseball");
melbournSoccer.addPlayer(soccerPlayer);
jerseeBaseball.addPlayer(baseballPlayer);
adelaideCrows.matchResult(ohioFotlball, 1,0);
melbournSoccer.matchResult(newyorkSoccer,6,4);
System.out.println("Ranking...");
System.out.println(adelaideCrows.getName()+": result:
"+adelaideCrows.ranking());
System.out.println(melbournSoccer.getName()+": result:
"+melbournSoccer.ranking());
System.out.println(jerseeBaseball.getName()+": result:
"+jerseeBaseball.ranking());
System.out.println(melbournSoccer.compareTo(newyorkSoccer));
System.out.println(adelaideCrows.compareTo(ohioFotlball));
Player class here from which another three classes FotballPlayer, SoccerrPlayer and BaseballPlayer inherits.
public abstract class Player{
private String name;
public Player(String name){
this.name = name;
}
public String getName(){
return name;
}
}
And here is Team class.
import java.util.ArrayList;
public class Team<T extends Player> implements Comparable<Team<T>>{
private String name;
int played = 0;
int lost = 0;
int won = 0;
int tied = 0;
private ArrayList<T> members = new ArrayList<>();
public Team(String name){
this.name = name;
}
public String getName(){
return name;
}
public boolean addPlayer(T player){
if(members.contains(player)){
System.out.println(player.getName()+" is already on this
team.");
return false;
}else{
members.add(player);
System.out.println(player.getName()+" has been added to team
"+this.name);
return true;
}
}
public int numPlayers(){
return this.members.size();
}
public void matchResult(Team<T> oponent, int ourScore, int theirScore){
if(ourScore > theirScore){
won++;
}else if(ourScore == theirScore){
tied++;
}else{
lost++;
}
played++;
if(oponent != null){
oponent.matchResult(null, theirScore, ourScore);
}
}
public int ranking(){
return (won * 2) + tied;
}
#Override
public int compareTo(Team<T> team){
if(this.ranking() > team.ranking()){
return -1;
} else if(this.ranking() < team.ranking()){
return 1;
}
else{
return 0;
}
}
}
Here are some clarifications to the questions.
Question 1:
Method ranking(). It doesn´t accept any parametr but returns result
from parametrs "won" and "tied". OK. But when we call this method like
this:
System.out.println(adelaideCrows.getName() + ": result: " + **adelaideCrows.ranking()**);
how the program knows values of "won" and "tied" for this
adealideCrows team? ...
Answer 1:
Consider this statement in the Main class: adelaideCrows.matchResult(ohioFotlball, 1, 0);. When this statement executes:
The adelaideCrows object gets affected. In the matchResult method the
instance variables won and tied are changed based on the method input
parameters (1 and 0, in this case).
When the statement adelaideCrows.ranking() is executed, the ranking() method uses the adelaideCrows's object instance variables won and tied (which were set earlier) to calculate the ranking ((won * 2) + tied) and return the value.
NOTES: See this article (my answer) on StackOverflow to get an idea about a Java class, an object, a reference, and class's attributes and behavior: Object References in Java.
Question 2:
And also here
System.out.println(melbournSoccer.compareTo(newyorkSoccer)); Does the
logic is the same? melbournSoccer reference is connected in method
public int compareTo(Team<T> team) to this.ranking() but reference
newyorkSoccer is connected to team.ranking()? So calling
this.ranking() invokes values stored in memory of reference
melbournSoccer and so on?
Answer 2:
Consider the statement: System.out.println(melbournSoccer.compareTo(newyorkSoccer));
Q). melbournSoccer reference is connected in method public int compareTo(Team<T> team) to this.ranking()
A). The keyword this refers to the current object - here it is melbournSoccer. this.ranking method gets the ranking for the melbournSoccer.
Q). Reference newyorkSoccer is connected to team.ranking()?
A). The method parameter compareTo() takes a Team as input - here it is a newyorkSoccer team object.
Q). So calling this.ranking() invokes values stored in memory of reference melbournSoccer and so on?
A). YES.
NOTES: Here is a link to Oracle's Java tutorials topic Using the this Keyword.
I try to answer your first question: The variables „won“ and „tied“ are instance variables. That means every time you create an object of your team class, the object gets its own „won“ and „tied“ variable to save data in it. You can access them with the name of the unique object (in your case the team name as example „adelaideCrows.won“ without the quotes). To answer the question about the „matchResult“ function: The function is related to your object again because you are not using „static“ declaration in front of the method name. So without static every instance of your class gets their own method so if you are passing parameters to that function they are passed into the objects function. If you want to save them you have to create a class variable (which is made with „static int“ as example) or a instance variable in order to save the data as long as the object exists, otherwise the data will get passed to the function and will be lost after the function execution is finished.
I wrote the below code, and as you see, in the constructor I call some methods to perform certain operations. And now what I am inquiring about is, whether it is a good practice to call those methods from the constructor OR declare those methods as public and instantiate an object from the class info, and let the object call those methods? What is the good practice for that?
Code:
class Info {
public RoadInfo(String cityName, double lat, double lng) throws FileNotFoundException, SAXException, IOException, XPathExpressionException {
// TODO Auto-generated constructor stub
this.cityname = cityName;
this.lat = lat;
this.lng = lng;
this.path = "c:"+File.separatorChar+this.cityname+".xml";
System.out.println(path);
this.initXPath();
this.method1()
this.method2()
..
this.expr = "//node[#lat='"+this.lat+"'"+"]/following-sibling::tag[1]/#v";
this.xPath.compile(this.expr);
String s = (String) this.xPath.evaluate(this.expr, this.document, XPathConstants.STRING);
System.out.println(s);
}
TLDR In my opinion, using methods inside of a constructor is a sign of bad design. If you aren't looking for design advice, then the answer "no there's nothing wrong with it, technically speaking, as long as you avoid calling non-final methods" should do you fine. If you ARE looking for design advice, see below.
I think your example code is not good practice at all. In my opinion, a constructor should only receive values which is relevant to it and should not need to perform any other initialization on those values. There's no way for you to test that your constructor 'works' with all of those little extra steps - all you can do is construct the object and hope that everything ends up in the correct state. Further, your constructor ends up with more than one reason to change, which violates the SRP.
class Info {
public RoadInfo(String cityName, double lat, double lng) throws FileNotFoundException, SAXException, IOException, XPathExpressionException {
// TODO Auto-generated constructor stub
this.cityname = cityName;
this.lat = lat;
this.lng = lng;
this.path = "c:"+File.separatorChar+this.cityname+".xml";
System.out.println(path);
this.initXPath();
this.method1()
this.method2()
..
this.expr = "//node[#lat='"+this.lat+"'"+"]/following-sibling::tag[1]/#v";
this.xPath.compile(this.expr);
String s = (String) this.xPath.evaluate(this.expr, this.document, XPathConstants.STRING);
System.out.println(s);
}
So, for example, this constructor is loading a file, parsing it in XPath.. if I ever want to create a RoadInfo object, I can now only do it by loading files and having to worry about exceptions being thrown. This class also now becomes hilariously difficult to unit test because now you can't test the this.initXPath() method in isolation, for example - if this.initXPath(), this.method1() or this.method2() have any failures, then every one of your test cases will fail. Bad!
I would prefer it to look something more like this:
class RoadInfoFactory {
public RoadInfo getRoadInfo(String cityName, double lat, double lng) {
String path = this.buildPathForCityName(cityName);
String expression = this.buildExpressionForLatitute(lat);
XPath xpath = this.initializeXPath();
XDocument document = ...;
String s = (String) xpath.evaluate(expression, document, XPathConstants.STRING);
// Or whatever you do with it..
return new RoadInfo(s);
}
}
Never mind the fact that you have at least 5 responsibilities here.
Build OS-neutral path
Build XPath expression for latitude/longitude
Create XPath doocument
Retrieve s - whatever that is
Create new RoadInfo instance
Each of these responsibilities (Except the last) should be separated into their own classes (IMO), and have RoadInfoFactory orchestrate them all together.
The purpose of the constructor is to establish the class invariants, that is, to bring the newly created object into a state that then allows clients to use them. In general, it is bad practice for an object to be relying on extra initialisation after it's constructed. What you want to avoid is to write such things into the documentation as:
...after creating an instance of class X, remember to ALWAYS call
initX(), or bad things will happen!
Though in certain cases it's difficult to avoid it and the constructor can become quite messy. For example loading external files in a constructor is problematic.
In these cases there are two things you can do:
Rewrite your constructor so it requires the contents of the file instead of the name. Let the caller do the loading. The main difference is that you require the caller to do something before the object is created, and you can express it with the signature of your constructor: public RoadInfo(String cityName, Document cityDatabase, double lat, double lng) {...} Of course you can go even further and require the value of s straight away and let the caller do the XPath search. Note that all these steps move the class towards having a single responsibility, which is considered a good thing.
But now you require the caller to perform many steps before they can build your RoadInfo. This is where you can use factories, which perform this extra initialisation too and return fully built RoadInfo objects.
The most important thing though is that the constructor must not call any method of the object under construction that can be overridden. Calling private methods is fine, calling public methods on this is not a good idea unless the methods or the class itself is marked as final.
If you call such a method, there's always a chance that the class overriding the method does something that breaks your functionality, like exposing this to the outside world before the construction is completed. Here's an example:
public abstract class Foo {
public Foo(String param) {
if (this.processParam(param) == null)
throw new IllegalArgumentException( "Can't process param.");
}
protected abstract processParam(String param);
}
public class Bar extends Foo {
public Bar(String param) {super(param);}
protected processParam(String param) {
SomeOtherClass.registerListener(this); // Things go horribly wrong here
return null;
}
}
If you now call new Bar("x"), the constructor of Foo will throw an exception because it considers the parameter invalid. But Bar.processParam() leaked a reference of this to SomeOtherClass, potentially allowing SomeOtherClass to use the Bar instance that shouldn't even exist.
More typically, classes requiring heavy initialization would be provided to the client via a factory method. Constructors are often too restrictive—a random example being the inability to surround the super or this opening call with try-catch.
If you provide a public factory method, you can make the constructor private. The constructor can only do the easy work like assigning final fields, and the factory takes over. In the long run this is a more future-proof design. Many public libraries had to break their earlier API to introduce factories that allow their code to grow.
Is it a good practice to call some methods from the constructor?
Sadly the only good answer to this is It depends on the object.
If the object is intended to hold information then the answer must be probably not, try to avoid it because an object should really only do one thing.
If, however, the object is there to perform a function then by all means make sure that it is ready to perform that function by calling methods etc. If, for example it is a database connection then you might wish to connect to the database at construct time, or at least register itself in a connection pool.
It is, however, good practice to postpone any potentially slow stuff you can postpone until you need it. In my example of the database you may wish to postpone the actual connection to the database but you would certainly register the connection in the connection pool.
Sadly - the answer to the opposite question:
Is it a bad practice to call some methods from the constructor?
Is also It depends on the object for similar reasons.
There's no good practice, just bad practice that you should not do.
When you call a method within a constructor, some dangerous here are:
1) the method can be overwritten, and its subclass implement break your class's constraint protected by constructor, the implement is out of your control.
class T {
int v;
T() {
v = getValue();
}
int getValue() {
return 1;
}
}
class Sub extends T {
#Override
int getValue() {
return -1;
}
}
here T's v suppose to be 1 when you call new T(), but when you create a new Sub(), 'v' will be set to -1, which may break T's constraint, and this happens unconsciously.
2) the half-constructed object leaked, while it's status may be illegal.
class T {
int a, b;
T(C c) {
// status of "this" is illegal now, but visible to c
c.calc(this);
a = 1;
b = 2;
}
}
class C {
int calc(T t) {
return t.a / t.b;
}
}
3) something more I don't know...
if you can prevent all of them, you can do what you want.
(Try to keep exceptions not thrown. So the constructor can nicely initialize a field.)
Do not call overridable methods in the constructor.
About the pitfalls of an overridable method call in a constructor:
The evaluation of a (child) constructor is:
"Zero" all fields (0, null, 0.0, false)
Call the super constructor (implicit if not in code)
Call all field initializations (field declarations with = ...)
Do rest of constructor code
So:
class A {
A() { f(); }
protected void f() { }
}
class B implements A {
String a;
String b = null;
String c = "c";
B() {
//[ a = null, b = null, c = null; ]
//[ super();
// B.f();
//]
//[ b = null; ]
//[ c = "c"; ]
// "nullA" - null - "c"
System.out.printf("end %s - %s - %s%n", a, b, c);
}
#Override
protected void f() {
System.out.printf("enter f : %s - %s - %s%n", a, b, c);
// null - null - null
a += "A";
b += "B";
c += "C";
// "nullA" - "nullB" - "nullC"
System.out.printf("leave f : %s - %s - %s%n", a, b, c);
}
}
That behavior is quite muddying the waters, and here doing assignments that are immediately overwritten by field initializations.
A normal call one often sees in constructors is a setter, that maybe has some normalization code. Make that setter public final void setX(X x);.
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.
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.
Is it possible to get a Object that is instanced in the Code by a String at Runtime?
Somthing like that:
public String xyz = "aaaa_bbb";
getObject("xyz").some function of String (e.g.: .split("_"))
Thanks
Here's an example
If it's a class field, you can get it by name like this.
import java.lang.reflect.Method;
public class Test {
public String stringInstance = "first;second";
public void Foo() {
try {
Object instance = getClass().getDeclaredField("stringInstance").get(this);
Method m = instance.getClass().getMethod("split", String.class);
Object returnValue = m.invoke(instance, ";");
if(returnValue instanceof String[])
{
for(String s : (String[])returnValue )
{
System.out.println(s);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String a[]){
new Test().Foo();
}
}
If it's a local method variable you are trying to invoke on, then you might be able to get at to the variable in from the current method from the call stack Thread.currentThread().getStackTrace() maybe.
It is hard to make out what you are asking, but you can fetch field values by name using reflection. Something like this:
Class c = this.getClass(); // or Someclass.class
Field f = c.getDeclaredField("xyz");
String value = (String) f.get(this);
... = value.split("_");
(I've left out a lot of exception handling ...)
But as a comment points out, if you are really trying to implement an associative array, there are better ways of doing this in Java; e.g. using a Map class.
You might have to rephrase the question.
If you just want to get the "aaaa" and "bbb" strings from the initial string, you can use StringTokenizer
If your String is a member field of your object, you can go take a look at the Field class.
However, I have to warn you that the code that you'll end up with will be by far longer than what you expect here. Indeed, you'll have to do some operations :
Get the Field obejct associated to xyz
Get method from its name and parameters list (using as an example Class#getDeclaredMethod(...))
Invoke the method on this particular instance
Each of these steps will eb a rather obscure line of code, with a bunch of throwed exceptions.
So, if you have an alternative, well, use it !
I have custom components on a jPanel and i would like to work with them without repainting them. I knwo if i use a List or Map that it is possible but i have to change the value in the Map and then repaint the GUI with the infomration in the Map.