what is variable- length argument list ?. demonstrate by an example code.
what is copy constructor ?. give an example
1
Expert's answer
2017-12-22T04:42:21-0500
Variable Length Argument Lists Since Java 5.0, methods can have a variable length argument list. Called varargs, these methods are declared such that the last (and only the last) argument can be repeated zero or more times when the method is called. The vararg parameter can be either a primitive or an object. An ellipsis (…) is used in the argument list of the method signature to declare the method as a vararg. The syntax of the vararg parameter is:
type... objectOrPrimitiveName The following is an example of a signature for a vararg method:
public setDisplayButtons(int row, String... names) {...} The Java compiler modifies vararg methods to look like regular methods. The previous example would be modified at compile time to:
public setDisplayButtons(int row, String [] names) {...} It is permissible for a vararg method to have a vararg parameter as its only parameter.
// Zero or more rows public void setDisplayButtons (String... names) {...} A vararg method is called the same way an ordinary method is called except that it can take a variable number of parameters, repeating only the last argument.
A copy constructor is a constructor that creates a new object using an existing object of the same class and initializes each instance variable of newly created object with corresponding instance variables of the existing object passed as argument. This constructor takes a single argument whose type is that of the class containing the constructor. Example
/** * Copy constructor. */ public Galaxy(Galaxy aGalaxy) { this(aGalaxy.getMass(), aGalaxy.getName()); //no defensive copies are created here, since //there are no mutable object fields (String is immutable) }
/** * Alternative style for a copy constructor, using a static newInstance * method. */ public static Galaxy newInstance(Galaxy aGalaxy) { return new Galaxy(aGalaxy.getMass(), aGalaxy.getName()); }
public double getMass() { return fMass; }
/** * This is the only method which changes the state of a Galaxy * object. If this method were removed, then a copy constructor * would not be provided either, since immutable objects do not * need a copy constructor. */ public void setMass(double aMass){ fMass = aMass; }
public String getName() { return fName; }
// PRIVATE private double fMass; private final String fName;
/** Test harness. */ public static void main (String... aArguments){ Galaxy m101 = new Galaxy(15.0, "M101");
"assignmentexpert.com" is professional group of people in Math subjects! They did assignments in very high level of mathematical modelling in the best quality. Thanks a lot
Comments