function - Purpose of a constructor in Java? -


what purpose of constructor? i've been learning java in school , seems me constructor largely redundant in things we've done far. remains seen if purpose comes about, far seems meaningless me. example, difference between following 2 snippets of code?

public class program {         public constructor () {         function();     }             private void function () {         //do stuff     }         public static void main(string[] args) {          constructor = new constructor();      } } 

this how taught things assignments, wouldn't below same deal?

public class program {         public static void main(string[] args) {         function();     }             private void function() {         //do stuff     } } 

the purpose of constructor escapes me, again we've done far has been extremely rudimentary.

constructors used initialize instances of classes. use constructor create new objects parameters specifying initial state or other important information object

from official java tutorial:

a class contains constructors invoked create objects class blueprint. constructor declarations method declarations—except use name of class , have no return type. example, bicycle has 1 constructor:

public bicycle(int startcadence, int startspeed, int startgear) {     gear = startgear;     cadence = startcadence;     speed = startspeed; } 

to create new bicycle object called mybike, constructor called new operator:

bicycle mybike = new bicycle(30, 0, 8);

new bicycle(30, 0, 8) creates space in memory object , initializes fields.

although bicycle has 1 constructor, have others, including no-argument constructor:

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

bicycle yourbike = new bicycle(); invokes no-argument constructor create new bicycle object called yourbike.


Comments

Popular posts from this blog

html - Firefox flex bug applied to buttons? -

html - Missing border-right in select on Firefox -

c# - two queries in same method -