+ 2

When will someone knows to use a constructor?

7th Feb 2018, 8:05 PM
AU Hameed
AU Hameed - avatar
3 odpowiedzi
+ 4
Basically, when you create classes you'll want to create a constructor to provide the variables with default values. As well, you can create a constructor with parameters so you can specify the values you want when instantiating the object. I create some code for you to use as an example to see what it does. https://code.sololearn.com/cvCIRMvkn57L/#java class Animal { private int legs; private String name; // default constructor public Animal(){ this.legs = 4; this.name = "dog"; } // constructor with arguments public Animal(int legs, String name){ this.legs = legs; this.name = name; } // SETTERS public void setLegs(int legs){ this.legs = legs; } public void setName(String name){ this.name = name; } // GETTERS public int getLegs(){ return this.legs; } public String getName(){ return this.name; } } public class Program { public static void main(String[] args) { // create object from default constructor Animal animal1 = new Animal(); // create object from constructor with arguments Animal animal2 = new Animal(2,"human"); // print the objects name and amount of legs System.out.println("Animal 1: " + animal1.getName() + " (" + animal1.getLegs() + ")"); System.out.println("Animal 2: " + animal2.getName() + " (" + animal2.getLegs() + ")"); // lets change some of their values with our setters animal1.setName("cat"); animal2.setName("bull"); animal2.setLegs(4); // print objects again to observe the changes System.out.println("Animal 1: " + animal1.getName() + " (" + animal1.getLegs() + ")"); System.out.println("Animal 2: " + animal2.getName() + " (" + animal2.getLegs() + ")"); } }
7th Feb 2018, 8:39 PM
Fata1 Err0r
Fata1 Err0r - avatar
+ 2
That's Great, thanks
7th Feb 2018, 11:08 PM
AU Hameed
AU Hameed - avatar