1 / 2

How to Use Overloaded Java Constructors

The example below shows a class with an overloaded constructor:<br><br>Java > cat Rectangle.java<br>class Rectangle<br>{<br>double width;<br>double height;<br>Rectangle()<br>{<br>width = 2;<br>height = 3;<br>}

softcrayons
Télécharger la présentation

How to Use Overloaded Java Constructors

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. How to Use Overloaded Java Constructors The example below shows a class with an overloaded constructor: Java > cat Rectangle.java class Rectangle { double width; double height; Rectangle() { width = 2; height = 3; } Rectangle(double w, double h) { width = w; height = h; } } Java > javac Rectangle.java Java > If you have a class like this, when you create members, you have a choice. You can accept the default settings or you can override them by supplying parameters. In the example below, r1 takes

  2. the default settings whereas r2 uses parameters to change the width to 4 and the height to 5: Java > cat RectangleExample.java public class RectangleExample { public static void main(String args[]) { Rectangle r1 = new Rectangle(); System.out.println(“r1 width = ” + r1.width); System.out.println(“r1 height = ” + r1.height); Rectangle r2 = new Rectangle(4,5); System.out.println(“r2 width = ” + r2.width); System.out.println(“r2 height = ” + r2.height); } } Java > javac RectangleExample.java Java > java RectangleExample r1 width = 2.0 r1 height = 3.0 r2 width = 4.0 r2 height = 5.0 Source : How to Use Overloaded Java Constructors

More Related