Overloaded constructors & getters and setters problem

I'm writing a driver class that generates two cylinders and displays some data. Problem is I don't understand the concept on overloaded constructors very well and seem to be stuck. What I'm trying to do is use an overloaded constructor for cylinder2 and getters and setters for cylinder1. Right now both are using getters and setters. Help would be appreciated.
Instantiable class
public class Silo2
    private double radius = 0;
    private double height = 0;
    private final double PI = 3.14159265;
    public Silo2 ()
        radius = 0;
        height = 0;       
   // Overloaded Constructor?
   public Silo2(double radius, double height) {     
      this.radius = radius;
      this.height = height;
   // Getters and Setters
   public double getRadius() {
      return radius;
   public void setRadius(double radius) {
      this.radius = radius;
   public double getHeight() {
      return height;
   public void setHeight(double height) {
      this.height = height;
   public double calcVolume()
       return PI * radius * radius * height;
   public double getSurfaceArea()
       return 2 * PI * radius * radius + 2 * PI * radius * height;
Driver class I'm not going to show all the code as it's rather long. Here's snippets of what I have so far
So here's input one using setters
validateDouble reads from a public double method that validates the inputs, which is working fine.
public static void main (String [ ]  args)
            Silo2 cylinder1 = new Silo2(); 
            Silo2 cylinder2 = new Silo2();
            //Silo inputs           
            double radSilo1 = validateDouble("Enter radius of Silo 1:", "Silo1 Radius");
            cylinder1.setRadius(radSilo1);
            double heiSilo1 = validateDouble("Enter height of Silo 1:", "Silo1 Height");
            cylinder1.setHeight(heiSilo1);
Output using getters
//Silo1 output
            JOptionPane.showMessageDialog(null,"Silo Dimensions 1 "   +
                '\n' + "Radius = " + formatter.format(cylinder1.getRadius()) +
                '\n' + "Height = " + formatter.format(cylinder1.getHeight()) +
                '\n' + "Volume = " + formatter.format(cylinder1.calcVolume()) +
                '\n' + "Surface Area = " + formatter.format(cylinder1.getSurfaceArea()));How can I apply an overloaded constructor to cylinder2?
Edited by: DeafBox on May 2, 2009 12:29 AM

DeafBox wrote:
Hey man,
My problem is that I don't now how to use an overloaded constructor. I'm new to this concept and want to use an overloaded contructor to display data for cylinder2, and getters and setters to display data for cylinder1.So, again, what in particular is your problem?
Do you not know how to write a c'tor?
Do you not know how to use a c'tor to intialize an object?
Do you not understand overloading?
Do you not realize that overloading c'tors is for all intents and purposes identical to overloading methods?

Similar Messages

  • Question about getters and setters

    I want to ask you a bit simple question. I know, you can show me google but i know to understand this by my example. My program code:
    class Readers {
         int age;
    public Readers(){
         age = 45;
    public int getAge() {
         return age;
    public void setAge(int age) {
         this.age = age;
    public void print_age(){
         System.out.println(+age);
    class Main {
         public static void main(String[] Args) {
         Readers john = new Readers();
         john.print_age();
    Why do i need use getters and setters? Because without these methods I get the same result. My program works correctly. Can you explain the benefit of using getters and setters?
    Thanks in advance ;)

    First, nobody said that you should use getters and setters in the first place. The only thing that's worse than dumb mutators/accessors would be the exposure of the attribute itself.
    Second, you certainly don't need mutators "internally".
    Third: consider you redesigning your class to store a person's birthdate instead of its age - makes sense if one thinks about it, doesn't it? If you have coded your entire program to access the "age" attribute of the object, you know have a problem because it was replaced by "birthday". The getter at least could calculate the current age from the birthdate - so no rewriting of the rest of your program would be necessary, just a small change in your getter.

  • Project Lombok - easier getters and setters

    I came across [Project Lombok|http://projectlombok.org/] recently and I think it greatly simplifies common Java patterns. All those getters and setters needed to satisfy JPA, JSF, and CDI make conceptually trivial classes become hundred-line monsters. If you need to change a type (e.g. int to long) or a name, then you need to do the same thing three or more times, or you can delete and generate everything again, but this can be risky: you might delete and regenerate a method that contained some little but necessary extra logic (a null check with ?:, for example), which could be indistinguishable from boilerplate code at first sight.
    I know this will be met with resistance, but I think a Lombok-like project should be incorporated into Java SE 8 or 9. Look at the great productivity improvements we had with Java 5 and Java 7 (specifically Project Coin). Look how easy it is to create an EJB in Java EE 6. People that would never consider EJBs in the past are now using them (me included) and enjoying!
    Maybe Java tools could at least provide official tools to support Lombok, because it currently uses unsupported interfaces to do its work.
    I think this post, if taken as an official feature request, would be off-topic here, but hey, I already have an account here and the conversation must start somewhere :-)

    MarcusF. wrote:
    All those getters and setters needed to satisfy JPA, JSF, and CDI make conceptually trivial classes become hundred-line monsters. Only when you're doing something very wrong design-wise. Getters and setters are no problem, you generate them anyway. But go ahead, keep believing the incredibly trivial is what is keeping you from being productive.
    Look how easy it is to create an EJB in Java EE 6.Yes its easier to CREATE an EJB. But it is still as hard as ever to understand the nuances of the technology and properly apply it without cutting into your own fingers. You still need to properly understand transaction management for example. But also stateless design, remote invocation, messaging, concurrency, etc. etc. Its still very, very hard. But yeah, annotations in stead of XML crud. That made -all- the difference right?
    It isn't code that makes things easier. It never was and it never will be. But people keep focusing on simplifying the actual programming by spitting out API after API and framework after framework and in the mean time the technology never gets any easier, or better. Because the code is not where the problem is.
    IMO of course.

  • [svn:osmf:] 10676: Removing JavaScript getters and setters: Wei found out that these are not supported by Internet Explorer.

    Revision: 10676
    Author:   [email protected]
    Date:     2009-09-29 07:06:03 -0700 (Tue, 29 Sep 2009)
    Log Message:
    Removing JavaScript getters and setters: Wei found out that these are not supported by Internet Explorer.
    Modified Paths:
        osmf/trunk/apps/samples/framework/HTMLGatewaySample/html-template/index.template.html
        osmf/trunk/framework/MediaFramework/org/openvideoplayer/gateways/HTMLGateway.as

    Hello ZeroThirtySeven,
    Do you mean that you want to use group policy to make users can visit the web application in Internet Explorer version 7?
    Enterprise Mode, a compatibility mode that runs on Internet Explorer 11 on Windows 8.1 Update and Windows 7 devices, lets websites render using a modified browser configuration that’s designed to emulate Internet Explorer 8.
    We could check if the web application can run in the Enterprise mode.
    If it can, please take a look at the following article to use group policy to turn on Enterprise Mode.
    http://msdn.microsoft.com/en-us/library/dn640699.aspx
    Please take a look at the following thread about set IE compatibility mode by group policy.
    https://social.technet.microsoft.com/Forums/windowsserver/en-US/95c0b8e6-72b5-472f-a5cb-07b17a8294a1/ie-compatibility-mode-not-applying-via-group-policy
    Best regards,
    Fangzhou CHEN
    Fangzhou CHEN
    TechNet Community Support

  • EJB newbie: Why getters and setters when I don't use them?

    I'd like to know why I have to write getters and setters in my bean implementaion class when I don't use them. I have SQL statements in my entity bean class that does querying and updates and I don't need to get or set individual fields of my databse.
    This must be a very trivial question for many, but I really dont know the answer to this one.
    Thanks.

    You can't get rid of them because they are built into iOS. It's annoying I know.

  • How struts invoking form getters and setters of a property

    hi,
    can anyone explain me how struts framework was calling the form properties getters and setters
    i have an idea like preparing a string such that
    if propert of text box is propertName, preparring a string with get and set making first letter capital
    setPropertyName
    getPropertyName
    and invoking that method in form property
    but i dont think this is the exact way struts follow , there could be a prcise and direct way to invoke propert methods
    i have another idea
    getting the declared method of the form class and search for the string propertyname in the methods name, and sure this is also not perfect way
    with regards
    satya

    can anyone tell where i can find libraries for access/manipulate beans.
    and sample example to invoke getters and setter of the property but not like preparing String "setPropertyName" or "getPropertyName" and invoking the method i beleive there should be standard way
    and also setPropertyName may take different type parameters i cannot keep number of if conditions to check for different datatypes
    with regards
    satya

  • Getters and Setters in ActionScript and ECMAScript

    Hi ,
    This line is taken from a book , here the Author mentions that
    In ActionScript , getters and setters is not necessary , they are a part of of the core ECMAScript language.
    Can anybody please let me know what is meant by ECMAScript language ??
    Thanks in advance .

    ECMAScript is an ECMA standard.
    Getters and setters are not mandatory (that's what they mean).
    However, they can be useful in many cases.
    - You can check the value in a setter before assigning (e.g checking if it's null)
    - You cannot override properties of a superclass but you can getters/setters just as you can methods
    - You can take some action when the value of the property is changed. There are many examples in UIComponent classes of the Flex framework.
    - You can put a breakpoint in a setter in order to debug data binding (see if it triggers)
    - In order to optimize data binding, you can write [Bindable event="YourCustomEventNameHere")] before the getter/setter and dispatch this event when the value is set so as to enhance performance of data binding (if you just write [Bindable], your properties will be processed by the framework even if their value does not change).
    Also, note how the synthax is different than Java.
    // ActionScript
    private var _myProperty:uint;
    public function get myProperty():uint
      return _myProperty;
    public function set myProperty(value:uint):void
      _myProperty = value;
    // Java
    private Integer myProperty;
    public Integer getMyProperty():
      return myProperty;
    public void setMyProperty(value:Integer):
      myProperty = value;
    Avoid creating getters/setters a la Java in ActionScript (i.e not using the get/set keywords). This is something I have seen in some implementations or auto-generated code from UML.

  • ValueRef'ing array elements, getters and setters

    Hi,
    I was wondering what the appropriate way to have the getters and setters for an array to be in the Model object.
    For example, what should the getter/setter for stuff in Stuff.java be?
    In the jsp page:
    <input_text .... valueRef="Stuff.stuff[0].property">
    In Stuff.java:
    private Blah[] stuff = new Blah[25];
    In Blah.java
    private String property;

    At a minimum,
    public Blah[] getStuff() { ... };Array accessors are always dangerous in Java, since they're necessarily mutable; if you don't want mutating, you have to clone the array every time you return it. Lists are preferable in this regard. OTOH, Lists aren't at all typesafe.
    -- Adam Winer

  • How to generater automatically getters and setters???

    Hi!!!
    Boys and Girls, how to generate automatically getters and setters like eclipse dialog or shortcut, using bea workshop(jpf file)?
    Best Regards,
    Pablo

    can anyone tell where i can find libraries for access/manipulate beans.
    and sample example to invoke getters and setter of the property but not like preparing String "setPropertyName" or "getPropertyName" and invoking the method i beleive there should be standard way
    and also setPropertyName may take different type parameters i cannot keep number of if conditions to check for different datatypes
    with regards
    satya

  • Do you need getters and setters for C types?

    Say, I have class declaration like so:
    @interface MyClass : NSObject
    int nValue;
    -(void)someMethod:(int)v;
    @end
    and then the implementation:
    #import "MyClass.h"
    @implementation MyClass
    -(id)init
    //Initialization
    if(self = [super init])
    nValue = 0;
    return self;
    -(void)dealloc
    [super dealloc];
    -(void)someMethod:(int)v
    int r = nValue;
    nValue += r + v;
    @end
    Do I need a getter and a setter for the 'nValue' variable?

    Den B. wrote:
    Do I need a getter and a setter for the 'nValue' variable?
    No more so than you would in C++.
    In Objective-C, if you really need to provide access to an objects internal values, you should you properties. If you don't need properties, then getters and setters are just as bad as they are anywhere.

  • Duplicate getters and setters

    Hi,
    Can any one tell me why do we need getters and setters both in class and backing bean? Is not a duplication?
    Here is an example
    In my class Dept I have getDept_Code,getDept_Name and setDept_Code,set_DeptName.
    and in my backing bean(DeptBean) I have same getters and setters.
    please note that in my Dept.jsp I use these as follows
    value="#{DeptBean.dept_code}".
    value="#{DeptBean.dept_name}"
    My question is why dont we use getters and setters in Dept class. and do we need to have getters and setters in backing bean?
    plz explain.

    You just can use the getters in Dept? You don't need to "flatten out the objects".
    MyDto:public class MyDto {
       private String field1;
       private String field2;
       // + getters + setters
    }MyBean:public class MyBean {
        private MyDto myDto;
        // + getter + setter
    }JSF<h:outputText value="#{myBean.myDto.field1}" />

  • Util to auto-generate getters and setters...

    Does anyone know of a utility that automatically generate getters and setter classes from a list of variable names???
    Might stop me getting RSI!

    i gave up on gets/sets about 2weeks after mylecturer
    introduced them to us :/Giving up on gets/sets is a mistake... take it from an
    EXPERIENCED programmer.you assume 2 much. Uni was a long time ago 4 me.
    >
    if a var can be modified, then make it public.Though
    adding a get/set method does provide encapsulation,it
    also requires more typing, bloats code and is alsoa
    fraction slower.Adding get/set methods provide more then just the
    encapsulation. It provides you easier debug not to
    mention easier way to read the code.Encapsulation encapsulates the idea of ezier debuggin :]
    gets/sets do not automatically give you code readability, and badly named gets/sets can detract from readability.
    >
    Sometimes gets/sets serve a purpose, but most ofthe
    time theyre just a waste of time.If you think set/get is a waste of time your attitude
    will get you into trouble. Consider code with a full
    set of public variables in a 'complex' system (well,
    lets just say 1500 classes).ok, you've applied my philosophy to your field, now let me apply yours to mine.
    I write games for Java enabled mobile phones(J2ME MIDP1.0), on this platform code size (and memory usage) is a SERIOUS concern.
    FYI. the Nokia 6310i mobile phone has approx. 140k of heap, and a jar size limited of 30k.
    EVERY line of code has to be optimal, in both space and time,
    The cost of gets/sets; inheritance; interfaces and all the other wonderful OO design features of java are serious performance inhibitors, and consequently are used only when absolutly necessary.
    >
    During development a bug is discovered and you realize
    that the bug is due to a change in a specific
    variable. How do you, quickly and simply, find out
    what classes are changing the variable. It could be
    anywhere; but by having a get and set method for that
    variable you could add a simple code like "new
    Exception().printStackTrace();" into the set method
    and get a trace when the bug happens. This way you
    would know within secondes what object is changing the
    variable making the debugging easy. don't write buggy code ;] (that was a j/k btw)
    btw, im curious how exactly do u realise that the bug is related to a specific variable? gets/sets help debugging, but they are not the magic bullet of debugging techniques.
    >
    What if you would like to override a class and to
    something before or after a variable is manipulated?
    This would be impossible if all variables are public.
    You will loose all control of you code.you are still argueing a different point to me - the abstraction of gets/sets do serve a purpose, however they also impose a cost.
    >
    There are many more reasons for adding the get/set
    methods but it will take me all day to write them all
    here.
    I say: "have all variables protected, GET OFF YOUR
    ASS, and add the 200 lines of code" if not for you
    then for the one that later will be using or fixing
    the code.
    Its quite funny watching a newbie programmer start
    writing a class, they identify the classes required
    attributes, then write 200lines of gets and sets
    before they even consider tackling the 'hard'bit[s]
    of the class :]What do think of code guidlines that are forced by
    most software companies? This is more important then
    most NEWBIES think; wait a few years and you will get
    the point..
    my point here, is that training programmers to follow guidelines before you have taught them the fundamentals of problem solving is futile.
    What about comments? Do you find them funny and
    useless? hope you don't...for your sake.no, all good code should be commented. But I have to admit, I don't waste time commenting code as i write it, i find it slows down my coding. However I will always go back and comment any code if it is to be used by some1 else.
    >
    Thinking it funny that people take the time and effort
    to make their code more readable, understandable,
    accessable, flexible and over all more pretty makes
    you the newbie.hmm, unprovoked flaming - now whos the newbie :/
    >
    It scares me to think that the new breed of
    programmers will think it funny to write GOOD code.
    bopen, bwise, bbetter...
    What frustrates me, is why good design always means slower performance.
    It shouldn't, and until Java progresses to the point where the runtime cost of good design is not significant, I will still regard Java as a primitive language.

  • Overloaded constructors, final and assert

    I am having some difficulties of using final variables and still have the ability to check parameters in the constructor.
    For example take this class:
    class MyObject {
    final String id;
    final String value;
    public MyObject(String id, String value) {
    assert id != null : "error";
    assert value != null : "error";
    this.id = value;
    this.value = value;
    public MyObject(Wrapper wrapper) {
    assert wrapper != null : "error";
    this(wrapper.getId(), wrapper.getValue());
    The above code won't compile because the assert is not allowed before the call to the other constructor.
    I cannot do the initializing of variables in a normal method, because I cannot assign to the variables at that point.
    I can use a static method that created to object, but is that really a good idea?
    Any suggestions?

    Generally, assert in parameters of public methods is not recommended.
    Assertion is for situations that are even more exceptional than Exceptions,
    for example, to detect bugs in the code.
    Theoretically, in public methods you don�t have to use assert to verify if the
    parameter is null or not null. You have to use if statement and throw
    NullPointerException,for example. If the method were private, like your
    init( ) method, so that�s ok and you could use assertion.It does not make sense to me why I would use asserts in private methods
    and not for public ones. Especially since the same parameters might
    end up in a private method anyway.
    For me asserts are about pre-conditions, post-conditions and constraints.
    I especially find them useful for pre-conditions and making very clear
    to the caller what I expect of him.
    A good article about assert can be found at javaworld
    http://www.javaworld.com/javaworld/jw-12-2001/jw-1214-assert.html
    Anyway, it's kinda off-topic, because if I would use an if statement
    and throw an exception, I have the exact same problem!
    This does not compile:
    public MyObject(Wrapper wrapper) {
        if (wrapper != null)
            throw NullPointerException("error");
        this(wrapper.getId(), wrapper.getValue());
    }

  • The TFO accelerator is overloaded (connection limit) and MAPI problems

    Hi All!
    Problem description:
    When MAPI acceleration (exchange/outlook) is Active in our WAAS environment, the remote site users randomly lose connection to the Exchange server (on hub site), if I disable the MAPI acceleration everything works ok.  so right now we are running with MAPI accelearation Disabled
    I can see that we often get max_conn_reject The TFO accelerator is overloaded (connection limit), we haven't done any adjustments to the default configuration. 
    The environment is one Hubsite with two remote sites.
    [Hub Site] 34mbit
    HW=OE674
    SW=4.1.5
    inline
    Enterprise Lic
    [Remote Site1] 4 mbit
    HW=OE474
    SW=4.1.5
    inline
    Enterprise Lic
    [Remote Site2] 4mbit
    HW=OE474
    SW=4.1.5
    inline
    Enterprise Lic
    So the question is how to solve this?!                                

    I had a feeling that you might have alot of computer remotely.
    One of the main factors in sizing a WAAS soluiton is to keep in mind the number of TCP connections that a single WAE can optimize.
    We limit the device on optimized TCP connections.After you hit the limit the device will go into the overload state that you mentioned.
    274 - 200 connections
    474 - 400 connections.
    Typically from a sizing a single workstation would be sized from 7-10 TCP connections.
    The 2nd factor in sizing is bandwidth - WAAS doesn't limit bandwidth but this is recommended for the CPU throughput.
    274 - 2 Megs
    474 - 4 Megs
    The 3rd factor is redundancy,. HA, etc.
    Thanks,
    Eric
         remember if this answrs your questions, please mark as answered and with a 5.

  • Proper Usage of getters and Setters in JSF

    I am getting a peculiar problem . Please see the snippet to get an idea .
    public List<Column> getColumnNameValueList(){
              List<Column> tempColumnNameValList = new ArrayList<Column>();
              // Fill the tempColumnNameValList           
              columnNameValueList.addAll(tempColumnNameValList);
              return columnNameValueList;
         public void setColumnNameValueList(List<Column> columnNameValueList) {
              this.columnNameValueList = columnNameValueList;
    In the screen I am displaying as --
    <h:panelGrid columns="3" rendered="#{updateRow.updatatable}"
                             styleClass="formtable">
                             <h:dataTable var="col" value="#{updateRow.columnNameValueList}"
                                  styleClass="formtable">
                                  <h:column>
                                       <h:outputText value="#{col.columnName}" />
                                       <h:outputText value="     :           " />
                                       <h:inputText value="#{col.columnValue}" />
                                  </h:column>
                             </h:dataTable>
                        </h:panelGrid>
    If I follow this approach, the setColumnNameValueList is called, when I update the value from the screen. But then I have to clear
    the columnNameValueList every time at the button actions.
    I have tried using this way ---
    public List<Column> getColumnNameValueList(){
         columnNameValueList = getColNameValList();
         return columnNameValueList;
    public List<Column> getColNameValList(){
         List<Column> tempColumnNameValList = new ArrayList<Column>();
         // Fill the tempColumnNameValList
         return tempColumnNameValList;
    Then Its not calling the setColumnNameValueList to update the value.
    Please help !!!!!!

    By setters, I mean the updated value is set as an when I am updating the values from the screen.
    I wanted to know the best approach . If you see in the approach 1, I have to clear the variable columnNameValueList after every button operation because the values are getting cached after every operation. Thats why I have to clear the columnNameValueList every time.
    Aproach 1
    public List<Column> getColumnNameValueList(){
    List<Column> tempColumnNameValList = new ArrayList<Column>();
    // Fill the tempColumnNameValList
    columnNameValueList.addAll(tempColumnNameValList);
    return columnNameValueList;
    public void setColumnNameValueList(List<Column> columnNameValueList) {
    this.columnNameValueList = columnNameValueList;
    If you see the Aproach 2, the updated values are not set.
    Aproach 2
    public List<Column> getColumnNameValueList(){
    columnNameValueList = getColNameValList();
    return columnNameValueList;
    public List<Column> getColNameValList(){
    List<Column> tempColumnNameValList = new ArrayList<Column>();
    // Fill the tempColumnNameValList
    return tempColumnNameValList;
    }

Maybe you are looking for

  • Can I use my Pioneer Inno with iTunes?

    Am I able to use my Pioneer Inno with iTunes?

  • RFC Sender Error - R/3 4.6C

    Hi, I try to do a RFC -> XI -> JDBC. When I execute the FM in my R/3 4.6C the following error show up: "connection to partner broken" / "CPI-C error CM_PRODUCT_SPECIFIC_ERROR". An error occurred when executing a Remote Function Call. "CPI-C error CM_

  • Acrobat 9 Pro install want Win Explorer and Installer to stop

    During an install of Acrobat 9 Pro on a Win7 laptop there's a message that Windows Explorer and Windows Installer are running and thus preventing installation of their components of Acrobat.  Reboots and disabling all start up programs doesn't fix it

  • Pdfs from illustrator in photoshop

    whenever i open up a pdf i saved from illustrator in photoshop in appears all pixelated. but open it in acrobat or anythin else it opens up grand. these would be all vector based designs so should all be smooth n crisp. ant ideas on how to remedy thi

  • How do you edit the style and fonts of the twitter feed in MuseCC

    After you embed a twitter feed into your MuseCC website how do you edit the style and fonts of the feed to match the design and copy of the site to keep the branding consistent