Java Constructors

Java Constructors

The constructors can appear anywhere in the code for the class. However, by convention, most people put them before any other functions that aren't constructors.

As for the variable names, all 6 are actually variable names, but the scope is differnet. The ones specified as parameters to the constructor (startCadence, startSpeed, startGear) are only available within the constructor. The other 3 (gear, cadence, speed) are probably class-wide variables, available to all methods. However the definition isn't shown in your code snippet. The full class would look mroe like:

class Bicycle
{
// class-level variables
private int gear;
private int cadence;
private int speed;

// constructor
public Bicycle(int startCadence, int startSpeed, int startGear) {
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}

// another method (not a constructor)
public void ShiftUp() {
gear = gear + 1; // notice the 'gear' variable is available here too.
}
}

Hope that helps!

Purpose of a constructor in Java?

Constructors are used to initialize the instances of your classes. You use a constructor to create new objects often with parameters specifying the initial state or other important information about the object

From the official Java tutorial:

A class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method declarations—except that they use the name of the class and have no return type. For example, Bicycle has one constructor:

public Bicycle(int startCadence, int startSpeed, int startGear) {
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}

To create a new Bicycle object called myBike, a constructor is called by the new operator:

Bicycle myBike = new Bicycle(30, 0, 8);

new Bicycle(30, 0, 8) creates space in memory for the object and initializes its fields.

Although Bicycle only has one constructor, it could have others, including a no-argument constructor:

public Bicycle() {
gear = 1;
cadence = 10;
speed = 0;
}

Bicycle yourBike = new Bicycle(); invokes the no-argument constructor to create a new Bicycle object called yourBike.

Do constructors always have to be public?

No, Constructors can be public, private, protected or default(no access modifier at all).

Making something private doesn't mean nobody can access it. It just means that nobody outside the class can access it. So private constructor is useful too.

One of the use of private constructor is to serve singleton classes. A singleton class is one which limits the number of objects creation to one. Using private constructor we can ensure that no more than one object can be created at a time.

Example -

public class Database {

private static Database singleObject;
private int record;
private String name;

private Database(String n) {
name = n;
record = 0;
}

public static synchronized Database getInstance(String n) {
if (singleObject == null) {
singleObject = new Database(n);
}

return singleObject;
}

public void doSomething() {
System.out.println("Hello StackOverflow.");
}

public String getName() {
return name;
}
}

More information about access modifiers.

Confused about java constructors

If I was to make an object in my main class like this: test object = new test("hey"); it would pass "hey" as a string to durp() right?

No, because your method durp() is not the Constructor. It's simply a method belonging to the class and can be called from a created living object.

public class Test {
/** this is a constructor */
public Test() {
}

/** this is also a constructor with a parameter */
public Test(String arg1) {
System.out.println(arg1);
}

/** this is a method of Test */
public void derp() {
}
}

You can read this tutorial from oracle about constructors

How do I call one constructor from another in Java?

Yes, it is possible:

public class Foo {
private int x;

public Foo() {
this(1);
}

public Foo(int x) {
this.x = x;
}
}

To chain to a particular superclass constructor instead of one in the same class, use super instead of this. Note that you can only chain to one constructor, and it has to be the first statement in your constructor body.

See also this related question, which is about C# but where the same principles apply.

what's the point of java constructor?

Constructors are what you use to initialize/set up the instances of your classes.

If you have an object that needs some processing before it is usable (initializing members for instance), you should do that in the constructor.

Ideally, you should never have "partially built" objects (i.e. objects that are "live", that you hold a reference to, but that are not yet usable). Without constructors, you'd be permanently creating partially built objects, and that is very error-prone. (Theory and practice don't always match, but keep that idea in mind.)

Two constructors?

That's the default (no-arg) constructor. Since you have another constructor, Java will not implicitly create it if you don't define it explicitly. Since the first line in your print method calls it, you'll get an error if you remove it.

Does a Java constructor return the Object reference?

No, actually, the constructors are compiled into the class file like methods having the name <init> and a void return type. You can see these "<init>" invocations in stack traces. The expression new Type() is compiled as an instruction new which just creates the instance of Type and an additional method invokation (invokespecial) to one of the constructors declared in Type.

The verifier will ensure that such a special method is invoked at exactly once on a newly created instance and that it is called before any other use of the object.

It’s just a programming language design decision to let constructors have no return type from the Java language point of view. After all, new Type(…) is an expression that evaluates to the newly created instance of Type and you can’t get a return value from the constructor with that programming language construct. Further, if you add a return type, Java will unconditionally assume that it is a method, even if it has the same name as the class.

That’s simply how it was defined: (It makes parsing the class definition easier)

The SimpleTypeName in the ConstructorDeclarator must be the simple name of the class that contains the constructor declaration, or a compile-time error occurs.

In all other respects, a constructor declaration looks just like a method declaration that has no result (§8.4.5).



Related Topics



Leave a reply



Submit