Java for Complete Beginners (Video), Part 18: Constructors

A tutorial on constructors in Java; what are they, how to create them, using multiple constructors with different parameters and calling constructors from within other constructors.

When the video is running, click the maximize button in the lower-right-hand corner to make it full screen.

Code for this tutorial:

class Machine {
	private String name;
	private int code;
	
	public Machine() {
		this("Arnie", 0);
		
		System.out.println("Constructor running!");
	}
	
	public Machine(String name) {
		this(name, 0);
		
		System.out.println("Second constructor running");
		// No longer need following line, since we're using the other constructor above.
		//this.name = name;
	}
	
	public Machine(String name, int code) {
		
		System.out.println("Third constructor running");
		this.name = name;
		this.code = code;
	}
}

public class App {
	public static void main(String[] args) {
		Machine machine1 = new Machine();

		Machine machine2 = new Machine("Bertie");
		
		Machine machine3 = new Machine("Chalky", 7);
	}

}

Third constructor running
Constructor running!
Third constructor running
Second constructor running
Third constructor running

 

Learn to program Java Swing with my complete video course – desktop programming and applets. Includes 7 free videos. Click here for details.

All pages on this site are copyright © 2013 John W. Purcell

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Posted in Java, Java Video Tutorials (Beginners) | Tagged , , , , , , |