Constructors
The first method most classes need is a constructor . A constructor creates a new instance of the class. It initializes all the variables and does any work necessary to prepare the class to be used. In the line website x = new website(); website() is a constructor. If no constructor exists Java provides a one, but it's better to make sure you have your own. You make a constructor by writing a public method that has the same name as the class. Thus our website constructor is called website(). Here's a revised website class with a constructor that initializes all the members to null Strings.
class website { String name; String url; String description; public website() { name = ; url = ; description = ; } } Better yet, we should create a constructor that accepts three Strings as arguments and uses those to initialize the member variables like so:
class website { String name; String url; String description; public website(String n, String u, String d) { name = n; url = u; description = d; } } We'd use this like so:
website x = new website("Cafe Au Lait, "http://metalab.unc.edu/javafaq/, "Really cool!); x.print(); This fits in well with the goal of keeping code relevant to the proper functioning of a class within the class.
However what if sometimes when we want to create a web site we know the URL, name, and description, and sometimes we don't? Best of all, let's use both!
class website { String name; String url; String description; public website(String n, String u, String d) { name = n; url = u; description = d; } public website() { name = ; url = ; description = ; } } This is called method overloading or polymorphism . Polymorphism is a feature of object oriented languages that lets one name refer to different methods depending on context. The important context is typically the number and type of arguments to the method. In this case we use the first version of the method if we have three String arguments and the second version if we don't have any arguments.
If you have one or two or four String arguments to the constructor, or arguments that aren't Strings, then the compiler generates an error because it doesn't have a method whose signature matches the requested method call.