What Is Overloading Constructors
Apr 6, 2014Can you give me a simple description of what overloading a constructer is?
View RepliesCan you give me a simple description of what overloading a constructer is?
View RepliesI am going through Thinking in Java, 4th Ed and I came across the section that talks about overloading variable arguments. I tried out a piece of code from the book. (Method and class names not exactly the same).
public class Varargs
{
public static void m1(Character... args)
{
System.out.println("Character");
[code]....
In the above code, the compiler throws an 'Ambiguous for the type varargs' error. The error goes away if the first method is changed to:
public static void m1(char c, Character... args)
why there is ambiguity in the first piece of code and not the second.
Why the following is happening.
For the below code, when I execute it, it prints
Short method 10 //result 1
Sub class short method 10 //result 2
Which is as expected but if I comment out line 3, then it prints
Integer method 10 //result 3
Integer method 10 //result 4
I can understand result 3 is because of an upcast from short to int, since FunWithOverloading will not have a overloaded method with short now. However, what is happening with result 4? Shouldn't it call methodA of the subclass with the argument type short? If its because I have declared the reference variable, derived, of the type FunWithOverloading, then how come the first result correctly picks the overloaded method of the sub class?
class FunWithOverloading{
void methodA(int x){System.out.println("Integer method " + x);}
void methodA(short x){System.out.println("Short method " + x);} //line 3
} class OverloadedSubClass extends FunWithOverloading{
void methodA(short x){System.out.println("Sub class short method " + x);}
[Code] ....
The class Overloading below asks for two names and prints three different greetings. Your task is to write the class methods missing from the class declaration. Methods print the greetings as shown in the example print. The names and parameter types of the needed methods can be checked from the main method because all methods are called there. This exercise also does not require you to copy the source code below to the return field. The method declarations will suffice.
Example output
Type in the first name: John
Type in the second name: Doe
Java Code:
import java.util.Scanner;
public class Overloading {
public static void main(String[] args) {
String firstName, secondName;
Scanner reader = new Scanner(System.in);
[code]....
why operator overloading is not supported in Java.
View Replies View RelatedWhat I have done wrong
public class BankAccount
{
String name;
int accountID;
double balance;
public void setAccount( String username, int ID, Boolean isJoint)
[Code] ....
The class Overloading below asks for two names and prints three different greetings. Your task is to write the class methods missing from the class declaration. Methods print the greetings as shown in the example print.
Hint:The names and parameter types of the needed methods can be checked from the main method because all methods are called there. This exercise also does not require you to copy the source code below to the return field.
The method declarations will suffice.
Example output
Type in the first name: John
Type in the second name: Doe
**********
Hi!
**********
Hi, John
**********
Hi, John and Doe
**********
import java.util.Scanner;
public class Overloading {
public static void main(String[] args) {
String firstName, secondName;
[Code] ....
I was told to create a class named Billing that includes three overloaded computeBill methods for a photobook store.
The first method takes the price of the book ordered, adds 8% tax and returns the total due.
The second method takes the price of the book, and the quantity, adds tax and returns the total.
The final method takes the price, quantity and a coupon discount, adds tax and returns the total.
All of this I have managed fairly well, although I keep getting a strange error at the end of my program that the constructor is undefined. The problem bits of code(the one throwing the errors) are under the comment //Enter values into each of the methods
Code:
package org.CIS406.lab2;
public class Billing {
//Declarations
double bookPrice;
int quantityOrdered;
double couponValue;
[Code] ....
My first thought was to create a constructor for each of the methods that I am using...
I have a case in which I want to sort two types of ArrayLists (using quicksort) and the method originally coded only accepts a String ArrayList. The problem is that now I want to sort an ArrayList of type int but couldn't . . . so I decided to overload the method. Since it looks very ugly to copy and paste the same chunk of code only to change the method signature I wondered if there is a better way to make this method more dynamic and be able to take in different types of ArrayLists.
My code:
private ArrayList<String> sort(ArrayList<String> ar, int lo, int hi){
if (lo < hi){
int splitPoint = partition(ar, lo, hi);
sort(ar, lo, splitPoint);
sort(ar, splitPoint +1, hi);
[Code] .....
why Java does not support return type in method overloading. I coded following and it compiles and runs without any errors.
class Ideone
{
public static void main (String[] args) {
sum(3,5);
[code]....
If Java did not support overloading based on return type, this program should not work, right?
Can i use constructors in an interface?
interface AI {
public abstract AI();
public abstract void hello();
}
Output:
I got the error as the method AI() should have return type.
Is it possible to combine two classes that I have defined to contain some of the same elements so that NetBeans stops giving me errors? I don't want to get rid of any necessary code, and if both classes are necessary, should I just rename one of them? One class is an ArrayList that I am using to write the information for employees entered to a text file "employee.txt." I also want users to be able to call on this information via employeeID in order to display employee information. The code is the following:
public ArrayList<Employee> getEmployees() {
// if the employees file has already been read, don't read it again
if (employees != null)
return employees;
employees = new ArrayList<>();
if (Files.exists(employeesPath)) // prevent the FileNotFoundException {
[code]....
The other class is a getEmployee class that I previously defined before attempting to read the information from the text file and display it in the console. It is as follows:
private void getEmployees() {
try {
// if the file doesn't exists, create it
if (!Files.exists(employeesPath))
Files.createFile(employeesPath);
BufferedReader in =
new BufferedReader(
new FileReader(employeesFile));
[code]....
I remember reading that a super() call to parent no-argument constructor is automatically inserted by compiler. So, if i have a chained hierarchy of classes (starting at top, with Object), will there be a chain of super() calls, going from bottom to top in the chain ? Will a super() call be inserted in child, if i provide a no-argument constructor for this class ?
View Replies View RelatedI am getting error in second constructor that I have created, it gives an error: cannot find symbol variable
package Objects;
import javax.swing.JOptionPane;
public class Constructor {
public static void main(String[] args) {
Piggybank1 pg1 = new Piggybank1("Abhinav", 500);
pg1.deposit(200);
pg1.withdraw(10);
[Code] ....
We are learning about how to pass objects into constructors. In our class, we made this following code:
public class InventoryItem {
//fields
private String description;
private int units;
//Add New constructor
public InventoryItem(InventoryItem some_object) {
description=some_object.description;
[Code] .....
As you can see the object of the same class is passed as the argument. Inside the constructor, our teacher did
some_object.description
This constructor, from my understanding, copies the description field and unit field to an object to the new object of class. Meanwhile, here is the demo class.
public static void main(String[] args)
{
//Create object
InventoryItem item1;
item1=new InventoryItem("hammer",20);
System.out.println("Item 1: ");
[Code] .....
Over here, my teacher uses :
.getDescription
My problem is that in the constructor of the first class I showed, why didn't he use
.getDescription
method instead of this
.description
May I know what is difference between these two. If I use .getdescription that would return the value of a field from that object too.
So while experimenting with constructors, repeating constructors with the same parameters, and with different parameters. I got an output -explaining how I got it.
I made 2 classes. a "support class" (has all the info) and an "execute class" (executes info).
Support:
package inschool;
public class Constructors {
String video;
public Constructors() {
video = "frozen";
[Code] ....
Execute:
package inschool;
//this is part of Constructors class
public class App{
public static void main(String[] args){
[Code] ....
The Output:
the video name is frozen
Second constructor running
Constructor running!
the video name is frozen
Output Explanation:
constructor call number 1 and 3 are the same (essentially) and both refer to the same constructor.
My Question: if both call #1 and #3 refer to the same constructor, why is the output for #1 "the video name is frozen"
while the output for #3 used both methods in the accessed constructor-with the resulting output as
"Constructor running!"
and
"the video name is frozen"
I double checked the output-and this time made sure to scroll up ... its the same result
I have a class named Cash shown below
public class Cash
{
//Quanity Field and RetailItem Object field
private int total_units;
private Retail myRetail;
//Create first constructors
public Cash()
{
this(0,null);
[Code] ....
I'm seriously need to understand the concept of making shallow copies and deep copies. My book has shown me that its better to perform deep copies and I have followed that method. if you guys look in my constructor of the cash class
//Create a a constructor
public Cash(int total_units,Retail myRetail)
{
this.total_units=total_units;
this.myRetail=new Retail(myRetail);
Apparently I have field in Cash Class named
Retail myRetail
When I pass in an argument from my demo, I'm making a copy of that object from the demo class. In my retail class, I have the following copy constructor .
//Make a copy constructor
public Retail(Retail Object1)
{
Item_Name=Object1.Item_Name;
Item_Number=Object1.Item_Number;
// if I use this then my program would work//this.cost=Object1.cost;
//if I use this part of code below, my program won't work at all and I would get an error saying Exception in thread "main" java.lang.NullPointerException
this.cost.Item_Cost=Object1.cost.Item_Cost;
this.cost.Wholesale_Cost=Object1.cost.Wholesale_Cost;
}
My question is why can't I perform a deep copy there. I know if I do
this.myRetail=myRetail
in my cash constructor it would work, but then the book says its not a good method;
class Test3 {
} class MySub extends Test3 {
}
class Test4{
public static void main(String args[]) {
MySub m = new MySub();
}
}
I learned that if a class and its parent class both have no constructors, the compiler is supposed to complain. When I compiled Test4, i got no errors. why did it give no errors?
I read this article : [URL] ....
In Java code, write class called Student with the following features:
• a private instance variable int studentNumber that is initialized to zero.
• a private instance variable String firstName;
• a private instance variable String lastName;
• a constructor which takes an integer argument and two String arguments to initializes the three respective data items.
• a public method with signature equals(Student s) . . .
So far this is my code :
public class student {
private int studentnumber = 0;
public student () {
firstname= "forename":
lastname="surname":
public student (integer studentnumber, string firstname, string lastname) {
this.firstname= firstname
this.lastname= lastname:
My question is how do i add the integer in the argument do i have to use int =? and how would i go about doing the public signature equals...
in abstract class constructors are not recommended since we don't call it directly ...my doubt is below code is right or wrong...
3public abstract class Concept
4{
5 private String id;
6
7 protected Concept( String anId )
8 {
9 if ( anId == null )
10 {
11 throw new NullPointerException( "id must not be null" );
12 }
13
14 id = anId;
15 }
MyStack class have by default some fixed size of maximum elements, allow user of your class to specify in constructor what this maximum size is. Also add possibility to specify name of the stack in constructor. User can either create object without parameters, can specify only size or name, or both of them. And also override function toString(), that this code will print:
[stack1] 4 6 1
[stack2] empty
MyStack s1 = new MyStack("stack1");
MyStack s2 = new MyStack("stack2");
s1.push(4);
s1.push(6);
s1.push(1);
System.out.println(s1.toString());
System.out.println(s2.toString());
You will need in total 5 constractor: default constructor (new Stack())
1-parameter constructor precising maximum size of the stack (new Stack(10))
1-parameter constructor giving the stack name (new Stack("My Stack"))
2-parameter constructor giving the maximum size and the name of the stack (new Stack("My Stack", 10))
"copy" constructor (Stack s1=new Stack(); Stack s2=new Stack(s1);)
I was required to make a program that contains 3 data fields, 2 constructors, and 4 methods. I'm having a hell of a time trying to put some input into this, where the user would choose from 1 of the 3 data fields I made up for car prices and choose their vehicle. As far as the constructors go, I made a default one but I'm not sure on how to A) implement another constructor and how do I involve the input into this and C) where the methods go in that.
I'm thinking of putting the input first but that ruins my constructors? I realize I asked a lot, but this is an online class without a text, and I'm basically starving for knowledge. [code]
public class Vehicle{
int truck;
int car;
int van;
[code]....
I have a class called Sprite which extends its several subclasses. Therefore, there are a lot of different Sprite classes, the thing is however, most of those subclasses have unique types of variables which I want to only be included in those particular subclasses, not anywhere else. For instance, I might have a variable measuring distance in one subclass, and in another subclass there might be a height variable inherent. I don't want the first subclass to have both variables, neither the second or the main class. Because before I initialize my subclasses, I need to create the constructors of those subclasses in the main Sprite class first because it doesn't have the unique variables which those classes consist of. How do I prevent that? Now I have to create the unique constructors and variables for every subclass, when I only want them in their associated classes.
View Replies View RelatedI have to create an application that deals with maps.
I first have to create the instance variables for the class.
So very simply if my hashmap is going to consist of football clubs and players. Football clubs being a string value for the key and players being a set of strings for the values. How would I go about creating the instance variable in a class for this?
I can't seem to find anything that specifically deals with instance variables and constructors for maps.
The end result is when I print the total it comes out to be 0. Trying to solve this
package pay;
import java.util.*;
public class manager
{
public manager(String string, int i, String type) {
[Code] ......
Java Code:
public class Puppy{
int puppyAge;
public Puppy(String name){
// This constructor has one parameter, name.
System.out.println("Passed Name is :" + name );
}
public void setAge( int age ){
puppyAge = age;
[Code] ....
How do I put 3 values of the each variable without replacing the last inputted one?
Like when I input "Tommy" and input another name "Gerald", "Tommy" won't be replaced by "Gerald" when I input again.