Can Call One Constructor From Two Different Constructors?

Nov 19, 2014

I 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] ....

View Replies


ADVERTISEMENT

How To Call A Constructor In Main

Jul 3, 2014

I am trying to call a constructor from PrepaidCard class in my main method, but I am not sure how to proceed.

As seen below, both the PrepaidCard constructor and the setCardID method have the ability to set the card ID.

public class PrepaidCard
{
public PrepaidCard(String id, int token) {
cardID = id;
tokenBalance = token;
}
public void setCardID(String id, int token) {
cardID = id;
tokenBalance = token;
}
}

Now in this block of code, I can successfully pass the id and token value by calling the setCardID method from the PrepaidCard class. Now I would like to call the PrepaidCard constructor from the PrepaidCard class to pass the id and token value, instead of using the setCardID method.

public class PrepaidCardTest
{
public static void main(String[] args) {
PrepaidCard card2 = new PrepaidCard(id, token);
System.out.print("Enter Card2 cardID: ");
id = input.nextLine();
card2.setCardID(id, token);
}
}

How to call the PrepaidCard constructor from the PrepaidCard class, to successfully pass the id and token value, in my main method?Specifically how to modify or replace this line of code so that it can correctly call the PrepaidCard constructor?

card2.setCardID(id, token);

View Replies View Related

Prepaid Card - How To Call A Constructor In Main

Jul 3, 2014

I am trying to call a constructor from PrepaidCard class in my main method, but I am not sure how to proceed.

As seen below, both the PrepaidCard constructor and the setCardID method have the ability to set the card ID.

Java Code:

public class PrepaidCard {
public PrepaidCard(String id, int token) {
cardID = id;
tokenBalance = token;
} public void setCardID(String id, int token) {
cardID = id;
tokenBalance = token;
}
} mh_sh_highlight_all('java');

Now in this block of code, I can successfully pass the id and token value by calling the setCardID method from the PrepaidCard class.

Now I would like to call the PrepaidCard constructor from the PrepaidCard class to pass the id and token value, instead of using the setCardID method.

Java Code:

public class PrepaidCardTest {
public static void main(String[] args) {
PrepaidCard card2 = new PrepaidCard(id, token);
System.out.print("Enter Card2 cardID: ");
id = input.nextLine();
card2.setCardID(id, token);
}
} mh_sh_highlight_all('java');

How to call the PrepaidCard constructor from the PrepaidCard class, to successfully pass the id and token value, in my main method?

Specifically how to modify or replace this line of code so that it can correctly call the PrepaidCard constructor?

Java Code: card2.setCardID(id, token); mh_sh_highlight_all('java');

View Replies View Related

Super Constructor Call - Creating Object

Sep 18, 2014

Its written that every constructor calls its super class constructor. And we know, constructors are called to create an object. Does it mean that if I am creating an object of a class, I am actually creating objects of all its super class???

View Replies View Related

Servlets :: Call Constructor / Method Upon Redirecting To Another Page?

Aug 13, 2014

I have login.jsp and home.jsp.

Each have its own servlets.

When I click Login button from login.jsp, it will navigate to home.jsp.

But before displaying home.jsp from he user, I want to call homeServlet.java's constructor/method.

This is because I want to populate a dropdown from home.jsp from a database.

I'm using MVC2 Servlet/JSP/Bean framework and AMAP, I do not want to execute javascripts/jquery for populating dropdowns.

View Replies View Related

How To Call EnrolStudent Method On Unit Constructor In Another Class When Create A New Unit

Mar 29, 2014

public Unit(String code, String name)
{
enrolStudent(student);
this.unitCode = code;
this.unitName = name;
}
public void enrolStudent(Student newStudent){
students = new ArrayList<Student>();
newStudent = new Student(24662496, "Kingsley", " Iwunze");
students.add(newStudent);
}

how can I call this enrolStudent() method on this Unit constructor in another class when I create a new Unit. all I need is to enroll students in units when units are created. below is my create unit method.

public void createUnits( ){
units = new ArrayList<Unit>();
units.add(new Unit("FIT2034", "Java Programming 2"));
units.add(new Unit("FIT2024", "Software Engineering"));
units.add(new Unit("MAT1830","Discrete Maths"));
unit.enrolStudent(new Student(25486321, "Julia", "Garcia"));
unit.enrolStudent(new Student(44589736, "James", "Olivia"));
unit.enrolStudent(new Student(47852103, "Lucky", "Thyriod"));
}

View Replies View Related

What Is Overloading Constructors

Apr 6, 2014

Can you give me a simple description of what overloading a constructer is?

View Replies View Related

Using Constructors In Interfaces?

Sep 1, 2014

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.

View Replies View Related

Two Classes With Identical Constructors?

Jun 3, 2014

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]....

View Replies View Related

Constructors In Class Hierarchy?

Feb 9, 2014

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 Related

Passing Objects To Constructors?

Mar 20, 2014

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.

View Replies View Related

Repeating Constructors With Same And Different Parameters

May 26, 2014

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

View Replies View Related

Copying Objects Through Constructors?

Apr 4, 2014

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;

View Replies View Related

Parent Class - No Argument Constructors

Mar 10, 2014

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] ....

View Replies View Related

Equals Signature / Constructors And Arguments

Jul 14, 2014

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...

View Replies View Related

Abstract Class Constructors Are Not Recommended

Aug 28, 2014

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 }

View Replies View Related

Write Constructors To MyStack Class

Jan 6, 2015

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);)

View Replies View Related

Java Coding For Constructors And Input

Oct 25, 2014

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]....

View Replies View Related

Create Unique Constructors And Variables For Every Subclass

Sep 10, 2014

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 Related

Creating Instance Variables And Constructors For Map Class

Mar 27, 2014

I 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.

View Replies View Related

Creating Program With Constructors And Calculate Result

Feb 11, 2015

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] ......

View Replies View Related

Constructors - How To Put 3 Values Of Each Variable Without Replacing Last Inputted One

Oct 2, 2014

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.

View Replies View Related

Fields / Getter And Setter Methods And Constructors

Mar 12, 2015

A blood clinic has hired a team of software developers to build a custom application to track patients. The clinic needs to keep a record of each patient and his or her blood data. Ultimately, they want all of the information stored in a database. As a starting point, the development team leader informs the team that the application has to have a set of core classes that represent the “real-world” entities the program needs to deal with. As a developer on the team, your job is to build a Patient class along with a BloodData class so that each Patient contains a BloodData object. This principle is known as “composition.”

Building the Framework Begin by creating a public Java class named PatientBuilder that contains a main method. Then, in the same file, create a non-public class named Patient and another named BloodType. Save the file as PatientBuilder.java. Note: If this was a real development project, you would put each class into it’s own file and put the files in the same folder. By combining them all into one file, we avoid having to submit three separate files, making it easier to keep all your work in one place.The BloodData Class This class should hold all of the attributes to hold the data the clinic needs for a given patient’s blood. Implement the following capabilities to accomplish this objective:

• Create a field to hold a blood type. The four possible blood types are O, A,B, and AB. For this project, you can simply define the field as a String.
• Create a field to hold the Rh factor. The two possible Rh factors are + and –.For this project, you can simply define the field as a String.
• Create getter and setter methods for both fields.
• Create a default constructor that sets the fields to “O” and “+”
• Create an overloaded constructor that accepts two parameters – one for a proposed blood type, and another for a proposed Rh. The constructor
should call the set methods and pass these parameter variables in to them.The Patient Class This class should hold all of the attributes to hold the data the clinic needs for a given patient’s blood. Implement the following capabilities to accomplish this objective:
• Create a field to hold an ID number along with get and set methods.
• Create a field to hold the patient’s age along with get and set methods.
• Create a field to hold the BloodData for a Patient. When declaring the field, initialize it by instantiating a BloodData object. Create get and set methods.
• Create a default constructor that sets the ID to “0”, age to 0, blood type of the BloodData object to “O”, and Rh value of the BloodData object to “+”.
• Create an overloaded constructor that accepts the following parameters: ID,age, blood type, and Rh. The constructor should call the set methods for the field associated with each parameter.The PatientBuilder Class.This class should contain the main method from which the program runs. In that method, implement the following functionality:• Ask the user for the ID, age, blood type, and Rh factor of a Patient.
• Create a Patient object, passing all of the data obtained from the user into the object.
• Write the code necessary to display the ID, age, blood type, and Rh factor of the Patient by calling the appropriate get methods of the object.

MY CODE ( which does not compile since it is wrong...)

import java.util.Scanner;
public class PatientBuilder
{
public static void main(String[] args){
String patientID;
int patientAge;
String patientRh;
String patientBlood;

[code].....

View Replies View Related

Using This Reference Variable On Constructors - Involve Objects?

Apr 2, 2014

I am trying to simplify my constructor by using "this" reference variable. I am aware how to use this reference when making constructors that involve fields of primitive data types; however, not so sure fields involving objects. I have made the following constructors and haver placed a question mark in the last parameter. How I can use this reference that involves objects.

public class RetailItem
{
//Create the fiels for item.
//You need item name and item number. then you would need
//cost
private String description;
private int Item_Number;
private CostData cost;
 
[Code] ....

View Replies View Related

Passing Values Into Constructors Using Main Or Static Method Functionality

Jan 24, 2014

I just kinda get stuck when it comes to passing values into constructors, using main method or static method functionality. In theory i kind of understand how it work but when i type it, it's totally different! I have to have a junit test too but i guess i could do that in the end.

I have attached the assignment. So, how to proceed with this:
 
public class Flight {
int flight_number, capacity, number_of_seats_left;
String origin, destination;
String departure_time;
double original_price;
 
[Code] ....

View Replies View Related

Month Class With Constructors And Getter / Setter Methods To Access Attributes

Jul 22, 2014

Write a class Month that represents one of the twelve months of the year. It should have three attributes for

the name of the month,

the number of days in the month, and

the birthstone.

Also add constructors and getter/setter methods to access the attributes.

You may use the following code to test your class.

Java Code:

import java.util.*;
public class Month
{
// ADD CODE HERE!!!
public static void main(String[] args)
{
Month[] months = new Month[12];

[Code] ....

So what I have added so far is (under public class month { :)

Java Code:

String monthName, monthBirthStone;
int monthDays;
public Month (String name, int days, String birthstone)
{
monthName = name;
monthBirthStone=birthstone;
monthDays=days;
} mh_sh_highlight_all('java');

So I believe that is the constructor. I still do not understand several things:

What would I need the getter and setter for?

I tested it using just the above code, and using month 1 I got:

Month@5a1cfb56

This makes sense as I obviously didn't do anything in order to get it in a String format for the array. But I do not understand this still - how would I get the constructor to output a string (to then be in the array?)

View Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved