Wednesday 2 March 2016

Method Overloading

JButton has more than one constructor. A class can have multiple constructors, each taking different parameters and presumably using them to do different kinds of setup. When a class has multiple constructors, Java chooses the correct one based on the types of arguments used with them. We call the JButton constructor with a String argument, so Java locates the constructor method of the JButton class that takes a single String argument and uses it to set up the object. This is called method overloading. All methods in Java (not just constructors) can be overloaded; this is another aspect of the objectoriented programming principle of polymorphism. Overloaded constructors generally provide a convenient way to initialize a new object. The JButton constructor we’ve used sets the text of the button as it is created:

 theButton = new JButton("Change Color");  
This is shorthand for creating the button and setting its label, like this:
 theButton = new JButton();  
 theButton.setText("Change Color");  

0 comments:

Post a Comment