Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 12 of 12

Thread: constructor

  1. #1
    Member
    Join Date
    Sep 2018
    Posts
    33
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default constructor

    Hello,
    I'm taking a class to learn how to program in Java, and I need to have two or more methods in my constructor that I can call from my main class. I can't seem to get it to work.
    Could someone show me the basic "building blocks" of calling multiple methods from a constructor? I've googled this, and watched a bunch of youtube videos, but I'm obviously doing something wrong.

  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    22,333
    Thanks
    53
    Thanked 2,393 Times in 2,347 Posts

    Default Re: constructor

    calling multiple methods from a constructor
    Calling a method from a constructor should be the same as calling a method from another method.

    doing something wrong.
    Please post the error messages you are getting that show the problem and the code.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Member
    Join Date
    Sep 2018
    Posts
    33
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: constructor

    thank you for the reply,
    I'm sorry, but I didn't think I was supposed to show error messages, here because this is theory and questions. I thought for errors it would go in "why doesn't my code work"
    I'm very new to Java, and just assumed that the structure of my program is wrong. For instance I just need to prompt the user for two different bits of information, so I inputted the Scanner utility, and used two println ( System.out.println) statements to ask the user for the input. But Eclipse is going on about duplicate statements, or something like that.
    I'm sorry I don't have specifics, but I thought I would post here to get a generic structure of a constructor with two methods I could call from the main.
    I could get the specific error if that would be more helpful.

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    22,333
    Thanks
    53
    Thanked 2,393 Times in 2,347 Posts

    Default Re: constructor

    Can you copy and paste here the compiler error messages and the code?
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Member
    Join Date
    Sep 2018
    Posts
    33
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: constructor

    will do, however, sorry, but it's at home. I'll post it as soon as I get back home.
    Thank you again for your help.

  6. #6
    Member
    Join Date
    Sep 2018
    Posts
    33
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: constructor

    Sorry for the slow reply, but I started working on it and was making progress. So I thought I had it fixed, but now I'm stuck again. In my code, I have to prompt the user for two separate inputs. So if the user, for the first input chooses product 1, and the quantity sold, I need to multiply the product 1 price by the quantity sold. I have a double for the product input price , and an integer for the quantity sold, but in my constructor these variables are in two separate methods. I can't figure out how to use a variable from one method in another method. I made an attempt, but my calculation is always coming up with the same output.
    here is what I have so far

     
    Sales
     
    // import java.util.Scanner;
     
    public class Sales {
     
        public static void main(String[] args) {
     
            SalesTest productNumberObject = new SalesTest ();
            productNumberObject.askProductNumber();
     
            SalesTest getproductNumberObject = new SalesTest ();
            getproductNumberObject.getProductNumber();
     
            SalesTest quantitySoldObject = new SalesTest ();
            quantitySoldObject.askQuantitySold();
     
            SalesTest getQuantitySoldObject = new SalesTest ();
            getQuantitySoldObject.getQuantityNumber();
     
        }
    }

     
    SalesTest
     
    import java.util.Scanner;
     
    public class SalesTest {
     
        double prodValue1 = 2.98;
        double prodValue2 = 4.50;
        double prodValue3 = 9.98;
        double prodValue4 = 4.49;
        double prodValue5 = 6.87;
        double calcValue1;
        double calcValue2;
        int age = 1;
     
     
     
        public void askProductNumber () {
     
            System.out.print("Please enter a product number( 1-5 ), (or 0 to stop)  ");
        }
     
        public void askQuantitySold () {
     
            System.out.print("Please enter the amount sold for the week:  ");
        }
     
        public void getProductNumber () {
     
            Scanner inputProductNumber = new Scanner(System.in);
            int inputProdNum = inputProductNumber.nextInt();
     
        }
     
        public void getQuantityNumber () {
     
            Scanner inputQuantitySold = new Scanner(System.in);
            int inputQuanNum = inputQuantitySold.nextInt();
     
            switch (age) {
     
            case 1:
                calcValue1 = inputQuanNum * prodValue1;
                System.out.print("Product 1: " + calcValue1);
                break;
            case 2:
                calcValue2 = inputQuanNum * prodValue2;
                System.out.print("Product 2: " + calcValue2);
                break;
            }        
        }
    }

  7. #7
    Member
    Join Date
    Sep 2018
    Location
    Virginia
    Posts
    284
    My Mood
    Cool
    Thanks
    0
    Thanked 38 Times in 36 Posts

    Default Re: constructor

    In your methods where you prompt for the input, don't declare the values in the method. Use instance fields in your class. For example declare int a, b in your class, and then simply set a and b in the appropriate method. Then those values will be available for use within the class.

    Regards,
    Jim

  8. #8
    Member
    Join Date
    Sep 2018
    Posts
    33
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: constructor

    Thank you so much for the reply. I'm very new to this, and had to Google instance fields, but I think I see what you're saying. I'll try that, thank you again.

  9. #9
    Member
    Join Date
    Sep 2018
    Location
    Virginia
    Posts
    284
    My Mood
    Cool
    Thanks
    0
    Thanked 38 Times in 36 Posts

    Default Re: constructor

    You're welcome. And for example, all of your double prodValues, etc are instance fields.

    Regards,
    Jim

  10. #10
    Member
    Join Date
    Sep 2018
    Posts
    33
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: constructor

    Wow! I guess that shows how new I am. I didn't know that!

    --- Update ---

    Wow! I guess that shows how new I am. I didn't know that!

  11. #11
    Member
    Join Date
    Sep 2018
    Posts
    32
    Thanks
    0
    Thanked 8 Times in 6 Posts

    Default Re: constructor

    A constructor is a special method that is used to initialize a newly created object and is called just after the memory is allocated for the object. It can be used to initialize the objects to desired values or default values at the time of object creation. It is not mandatory for the coder to write a constructor for a class.

    If no user-defined constructor is provided for a class, compiler initializes member variables to its default values.

    numeric data types are set to 0
    char data types are set to null character(\0)
    reference variables are set to null

    Rules for creating a Java Constructor
    It has the same name as the class
    It should not return a value not even void
    Example 1: Create your First Constructor Java

    Step 1) Type following code in your editor.

    class Demo{
    int value1;
    int value2;
    Demo(){
    value1 = 10;
    value2 = 20;
    System.out.println("Inside Constructor");
    }

    public void display(){
    System.out.println("Value1 === "+value1);
    System.out.println("Value2 === "+value2);
    }

    public static void main(String args[]){
    Demo d1 = new Demo();
    d1.display();
    }
    }
    Step 2) Save , Run & Compile the code. Observe the output.

    Output:

    Inside Constructor
    Value1 === 10
    Value2 === 20
    Constructor Overloading
    Constructor overloading is a technique in Java in which a class can have any number of constructors that differ in parameter list. The compiler differentiates these constructors by taking into account the number of parameters in the list and their type.

    Examples of valid constructors for class Account are

    Account(int a);
    Account (int a,int b);
    Account (String a,int b);

  12. #12
    Member
    Join Date
    Sep 2018
    Posts
    32
    Thanks
    0
    Thanked 8 Times in 6 Posts

    Default Re: constructor

    Data types aren’t much use unless you can do things with them. For this purpose classes have methods. Members say what a class is. Methods say what a class does. For instance our website class might have a method to print its data. If so that would look like this:

    class website {

    String name;
    String url;
    String description;

    print() {
    System.out.println(name + ” at ” + url + ” is ” + description);
    }

    }

    Outside the website method we call the print method just like we referenced the member variables, using the name of the particular object we want to print and the . operator.

    website x = new website();

    x.name = “Cafe Au Lait”;
    x.url = “http://metalab.unc.edu/javafaq/”;
    x.description = “Really cool!”;

    x.print();

    Notice that within the website class we don’t need to use x.name or x.url. name and url are sufficient. That’s because the print method must be called by a specific instance of the website class, and this instance knows what its data is. Or, another way of looking at it, the every object has its own print method.

    The print() method is completely enclosed within the website class. All methods in Java must belong to a class. Unlike C++ programs, Java programs cannot have a method hanging around in global space that does everything you forgot to do in your classes.

    Constructors
    The first method most classes need is a constructor. A constructor creates a new instance of the class. It initializes all the variables and does any work necessary to prepare the class to be used. In the line website x = new website(); website() is a constructor. If no constructor exists Java provides a default one, but it’s better to make sure you have your own. You make a constructor by writing a public method that has the same name as the class. Thus our website constructor is called website(). Here’s a revised website class with a constructor that initializes all the members to null Strings.

    class website {

    String name;
    String url;
    String description;

    public website() {
    name = “”;
    url = “”;
    description = “”;
    }

    }

    Better yet, we should create a constructor that accepts three Strings as arguments and uses those to initialize the member variables like so:

    class website {

    String name;
    String url;
    String description;

    public website(String n, String u, String d) {
    name = n;
    url = u;
    description = d;
    }

    }

    We’d use this like so:

    website x = new website(”Cafe Au Lait”, “http://metalab.unc.edu/javafaq/”, “Really cool!”);
    x.print();

    This fits in well with the goal of keeping code relevant to the proper functioning of a class within the class.

    However what if sometimes when we want to create a web site we know the URL, name, and description, and sometimes we don’t? Best of all, let’s use both!

    class website {

    String name;
    String url;
    String description;

    public website(String n, String u, String d) {
    name = n;
    url = u;
    description = d;
    }

    public website() {
    name = “”;
    url = “”;
    description = “”;
    }

    }

    This is called method overloading or polymorphism. Polymorphism is a feature of object oriented languages that lets one name refer to different methods depending on context. The important context is typically the number and type of arguments to the method. In this case we use the first version of the method if we have three String arguments and the second version if we don’t have any arguments.

    If you have one or two or four String arguments to the constructor, or arguments that aren’t Strings, then the compiler generates an error because it doesn’t have a method whose signature matches the requested method call.

    toString Methods
    Print methods are common in some languages but most Java programs operate differently. You can use System.out.println() to print any object. However for good results your class should have a toString() method that formats the objects data in a sensible way and returns a String. Here’s how we’d implement it in the website example:

    public class ClassTest {

    public static void main(String args[]) {

    website x = new website(”Cafe Au Lait”, “http://metalab.unc.edu/javafaq/”, “Really cool!”);
    System.out.println(x);

    }

    }

    class website {

    String name;
    String url;
    String description;

    public website(String n, String u, String d) {
    name = n;
    url = u;
    description = d;
    }

    public website() {
    name = “”;
    url = “”;
    description = “”;
    }

    public String toString() {
    return (name + ” at ” + url + ” is ” + description);
    }

    }

Similar Threads

  1. which class has a default constructor? (Req. guidance on constructor)
    By DragBall in forum Java Theory & Questions
    Replies: 1
    Last Post: June 27th, 2012, 04:42 PM
  2. creating constructor
    By msinc210 in forum Object Oriented Programming
    Replies: 4
    Last Post: May 31st, 2012, 12:15 AM
  3. Constructor
    By kbbaloch in forum Object Oriented Programming
    Replies: 6
    Last Post: February 1st, 2012, 10:40 PM
  4. Constructor help
    By sambar89 in forum Object Oriented Programming
    Replies: 3
    Last Post: November 26th, 2011, 10:17 PM
  5. Copy Constructor
    By Rhyssa6 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: April 23rd, 2011, 10:43 PM