Reputation: 93
I have started learning core Java and one particular thing is driving me crazy. I know how create a object
something like
Mouse mouse = new Mouse ();
However what I don't understand is whether these are objects too:
Connection conn = DriverManager.getConnection(url, user, password);
Statement st = conn.createStatement();
ResultSet rs1 = st.executeQuery("");
If not - what are they? Would really appreciate if someone can clear my confusion.
Upvotes: 0
Views: 113
Reputation: 39287
We can expand your mouse example:
class Mouse {
private String name;
public Mouse() {
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public Mouse makeDropping() {
return new Dropping(this);
}
public static Mouse createMouse(String name) {
Mouse mouse = new Mouse();
mouse.setName(name);
return mouse;
}
}
class Dropping {
private Mouse;
public Dropping(Mouse mouse) {
this.mouse = mouse;
}
public String mouseName() {
return this.mouse.getName();
}
}
We can create a mouse object using the constructor:
Mouse mickey = new Mouse();
mickey.setName("Mickey");
new Mouse()
creates the object, mickey
is a reference to that object.
We can also create a mouse using the static factory method of the Mouse class:
Mouse jerry = Mouse.createMouse("Jerry");
Mouse.createMouse("Jerry")
returns a reference to the Mouse object it created and we set it to jerry
.
Now if we call the makeDropping()
method on either Mouse
, they return a Dropping
object.
Dropping mickeyDropping = mickey.makeDropping();
Dropping jerryDropping = jerry.makeDropping();
We don't need to know where the Dropping
object is created, we still have a reference to a Dropping
object.
String name1 = mickeyDropping.mouseName();
String name2 = jerryDropping.mouseName();
Calling the mouseName()
method on the Dropping objects also returns references, this time to a String.
Upvotes: 1
Reputation: 3809
Yes, conn
, st
, and rs1
in your samples are all objects, just like mouse
. You are creating a mouse with a constructor, like so:
Mouse mouse = new Mouse()
But you just as easily could add a static
method to your Mouse
that would create a new instance of mouse
, just like DriverManager.getConnection(url, user, password);
returns a new instance of Statement
. For example:
public class Mouse {
public Mouse() { }
public static Mouse createNewMouse() {
return new Mouse();
}
}
Then instead of using the constructor you could just as easily say
Mouse mouse = Mouse.createNewMouse();
In the case of the Mouse
class, there is no good reason to use static method like that. As some of the comments have mentioned, however, there is something called the Factory Method which is a design pattern that can hide some of the complexity of instantiating complex objects.
Upvotes: 3
Reputation: 1
Yes : conn, st and rs1 are objects (instances), even if you didn't instantiate them directly.
For example conn:
Upvotes: 0