Get/set methods

I've been programming in java for a while now, but just recently i started wondering about something. Doesn't get/set methods that contain no other code defeat the point of encapsulation? i.e
public void getXxx() {
return xxx;
But now to the important question. Does the javac compiler inline get/set methods and if yes, how does it work around the private access to the data members?

yes you are right. first all variables should be private (there are some cases where protected is useful). that being hte case, all access methods do is expose the way this class does its storage. and will break if that changes. for example, a rectange using int for width and height, has corresponding setWidth( int ), getHeight() etc. now the author of the class changes int to a Point. now there should only be get/setPoint and the previous should be removed. this changes the API and breaks code using this class.
Lets say one keeps the setWidth etc as 'doing no harm', then the question is why does one need this? commonly used in eg
setWidth( getWidth() + 10 );
to lenghten the width.
A better way is to capture this need in the messaging system. therefore have a method:
widenBy( int w ) {
width += w;
notice this way, when changing the private width variable from int, to Point, to Long or any other, does not break code. there is no need to tidy up the access methods either.
classes that have no behaviour are often created to group variables together and passed along for convenience. These are not strictly classes. Then why not have variables public and save the method calls to access methods. Having access methods does not make it more OO. These 'classes' should be defined as inner classes of the enclosing class.
I've been programming in java for a while now, but
just recently i started wondering about something.
Doesn't get/set methods that contain no other code
defeat the point of encapsulation? i.e

Similar Messages

  • Confusion about get/set method not working

    Hi
    Hopefully someone can point out the elementary mistake I have made in my code. I have created a get/set method to hold a value"total" so that I can then get it to display it further down my code in an HTML page. I am setting the value as I can check this by printing it out (line 102) but when I try to use it again it displays 0.0. What have I done wrong?
    class ReportListener implements ActionListener
         Context context;
         ResultSet resultAll;
         ResultSet resultTotal;
         JFrame frame;
         int daysInMonth;
         int i;
         DisplayCurrencyOnBills d;
         DateFormatSymbols symbols;
         String[] newWeekday;
         Date theDate;
         String date;
         ReportListener (Context theContext)
              context = theContext;
         public void actionPerformed(ActionEvent e)
           try
              printWeeklyReport();
              //countDaysInMonth();
              getReportMoneyTotal();
         catch (SQLException s)
                   s.printStackTrace();
         public void countDaysInMonth()
         public void getReportMoneyTotal() throws SQLException
              Calendar todayTotal =Calendar.getInstance() ;
               SimpleDateFormat reportDateFormat = new SimpleDateFormat("dd MM yyyy");
              PreparedStatement preparedT =context.getConnection().prepareStatement(
                   "SELECT Sum(tblSession.Fee) AS Total, Count(tblBooking.BookingID) AS CountOfBookingID FROM tblSession INNER JOIN "+
                   "(tblBooking INNER JOIN tblCustomer_Booking ON tblBooking.BookingID = tblCustomer_Booking.BookingID) ON tblSession.SessionID = tblBooking.SessionID "+
                   "WHERE (((tblBooking.EventDate)>DateAdd('m',-1,#"+reportDateFormat.format(todayTotal.getTime())+"#)) AND ((tblSession.Session)='Morning' Or (tblSession.Session)='Evening')) OR (((tblSession.Session)='Afternoon') AND ((tblBooking.Extension)=Yes))"
              ResultSet resultTotal =preparedT.executeQuery();
              resultTotal.next();
              double total =resultTotal.getDouble("Total");     
              context.setReportIncomeTotal(total);
              System.out.println("Line 102 "+context.getReportIncomeTotal());
              preparedT.close();
         public void printWeeklyReport() throws SQLException
              Calendar today =Calendar.getInstance() ;
               SimpleDateFormat reportDateFormat = new SimpleDateFormat("dd MM yyyy");
              PreparedStatement prepared =context.getConnection().prepareStatement(
                   "SELECT tblBooking.EventDate, tblSession.Session, tblBooking.Extension, tblSession.Fee, Count(tblBooking.BookingID) AS CountOfBookingID "+
                   "FROM tblSession INNER JOIN (tblBooking INNER JOIN tblCustomer_Booking ON tblBooking.BookingID = tblCustomer_Booking.BookingID) ON "+
                   "tblSession.SessionID = tblBooking.SessionID GROUP BY tblBooking.EventDate, tblSession.Session, tblBooking.Extension, tblSession.Fee "+
                   "HAVING (((tblBooking.EventDate)>DateAdd('m',-1,#"+reportDateFormat.format(today.getTime())+"#)) AND ((tblSession.Session)='Morning' Or "+
                   "(tblSession.Session)='Evening')) OR (((tblSession.Session)='Afternoon') AND ((tblBooking.Extension)=Yes))"
              ResultSet resultAll =prepared.executeQuery();
              resultAll.next();
              System.out.println("Line 123 "+context.getReportIncomeTotal());
                        PrintWriter printWriter;
                        try
                             JFileChooser fc=new JFileChooser();
                             int returnVal = fc.showSaveDialog(frame);
                             if (returnVal != JFileChooser.APPROVE_OPTION)
                                  return;
                             FileOutputStream outputStream=
                                  new FileOutputStream(fc.getSelectedFile());
                             OutputStreamWriter writer=
                                  new OutputStreamWriter(outputStream,"UTF-8");
                             printWriter=new PrintWriter(writer);     
                           printWriter.println("<html><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'><body><h1>Monthly Usage Statistics</h1>");
                           printWriter.println("<table width='100%' border='1'><tr><td width='100%' colspan='8'><h2 align='center'>Monthly Summary</h2></td></tr>");
                         System.out.println("Line 152 "+context.getReportIncomeTotal());
                         int count = 0;
                             while ( resultAll.next() )
                              count++;
                              String session = resultAll.getString("Session");
                              Double fee= resultAll.getDouble("Fee");
                           // display currency correctly
                         //double d=Double.parseDouble(fee);
                         Locale locale = new Locale("GBP");
                         NumberFormat gbpFormat = NumberFormat.getCurrencyInstance(locale);
                             symbols = new DateFormatSymbols(new Locale("en"));
                         newWeekday =symbols.getWeekdays();
                             SimpleDateFormat formatter = new SimpleDateFormat("EEEE",symbols);
                             Date theEventDate = new Date();
                             theEventDate=resultAll.getDate("EventDate");
                             date = formatter.format(theEventDate);
                             // set date for Usage Report
                             Calendar reportDate = Calendar.getInstance();
                             Calendar reportToday =Calendar.getInstance();
                             reportDate.add(Calendar.MONTH,-1);
                             SimpleDateFormat reportFormat = new SimpleDateFormat("EEEE ,dd MMM yyy");     
                             //setDecimalFormat for report total
                             DecimalFormat decFormat = new DecimalFormat(".##");
                             printWriter.println(
                             "<tr><td width='100%' colspan='8'>For month from "+reportFormat.format(reportDate.getTime())+" to "+reportFormat.format(reportToday.getTime())+"</td></tr><tr><td width='100%' colspan='8'>Total amount of income from occasional bookings "+decFormat.format(context.getReportIncomeTotal())+"</td>"+
                               "</tr><tr><td width='100%' colspan='8'>Percentage use for all bookings</td></tr><tr><td width='8%'></td><td width='8%'>MON</td><td width='9%'>TUES</td>"+
                            "<td width='9%'>WEDS</td><td width='9%'>THURS</td><td width='9%'>FRI</td><td width='9%'>SAT</td><td width='9%'>SUN</td></tr><tr><td width='8%'>AM</td><td width='8%'></td>"+
                            "<td width='9%'></td><td width='9%'></td><td width='9%'></td><td width='9%'></td><td width='9%'></td><td width='9%'></td></tr><tr><td width='8%'>PM</td><td width='8%'></td>"+
                            "<td width='9%'></td><td width='9%'></td><td width='9%'></td><td width='9%'></td><td width='9%'></td><td width='9%'></td></tr><tr><td width='8%'>EVE</td><td width='8%'></td>"+
                            "<td width='9%'></td><td width='9%'></td><td width='9%'></td><td width='9%'></td><td width='9%'></td><td width='9%'></td></tr>"
                             System.out.println(count);
                             printWriter.println("</table>");
                             printWriter.println("</body></html>");
                             printWriter.close();
                             prepared.close();
                             JDialog reportDialog=new JDialog(frame);
                             reportDialog.setSize(800,600);
                             JEditorPane editorPane=new JEditorPane(fc.getSelectedFile().toURL());
                             editorPane.setContentType("text/html; charset=UTF-8");
                             reportDialog.getContentPane().add(editorPane);
                             reportDialog.setVisible(true);
                        catch (IOException exception)
                             exception.printStackTrace();
         This code finds data from a database(this works as it also prints a report). Here is the extraxt of my get/set method which is located in a "context" class.
    public void setReportIncomeTotal(double total)
              this.total=total;
         public double getReportIncomeTotal()
              return total;
         }I'd be grateful for any help.

    but when I try to use it again it displays 0.0This seems to mean that either the value has been reset or you are calling the method on another (new) ReportListener.
    It's hard to say, as you didn't provide us with the code sample that illustrate the corresponding scenario (did you?.)
    Note that I didn't get into details, but I just noticed that your actionPerformed method first print weekly report, and then get the money total. (Shouldn't it be the opposite order?)

  • Getter & Setter Method not getting called for a field enhanced through AET

    Hello,
    I am new to SAP CRM 7.0 and working on a requirement.
    A Z-field was added by our functional guy in CRM 7.0 WebGui through AET in the 'Create Opportunity' transaction (Header data).
    Now the requirement is, as soon as the opportunity is created through the WebGui, I should post a document in R/3 and paste that document number back to the enhanced Z-field in opportunity.
    Work done by me:
    I pressed F2 on the enhanced Z-field in the WebGui screen and took the details of view, component name etc. After this I went to normal SAP CRM system and open tcode "BSP_WD_CMPWB", located the corresponding view "BT111H_OPPT/Details" and right clicked & enhanced the same.
    Then I opened the structure of this view, expanded context node, located context "BTOPPORTH" and inside this, located my Z-attribute. Now right clicked on the Z-attribute & selected the option "Generate SETTER & GETTER Methods" and these were generated successfully.
    Problem:
    The problem is even after putting external break points in these methods, these methods are not getting called while creating, modifying & displaying the Opportunity in WebGui.
    I hope that for the requirements that I have, I have to do the coding in "Getter & Setter" methods. But since these are not getting called, I am unable to proceed.
    Please help/suggest how to achieve this.
    Thanks in anticipation.
    Best Regards,
    Rahul Malani

    Hi,
    If you can see the field in UI and still get_ method is not being triggered then try to regenerate these methods. If it still doesn't work then please look for SAP notes or raise an OSS.
    There should be some note for the issue you faced.
    please refer:
    Help Needed immediately - AET getter setter methods not getting triggered
    Regards,
    BJ

  • Change the properties of a field dynamically using Getter/Setter methods

    Thanks
    Raj
    Edited by: RajICWeb on Aug 12, 2009 4:31 AM

    Hi Harshit
    Thanks for the reply. Like you suggested, I redefined the get_i_zfield( ) method. But the program is not going through this method.
    FYI.....I created the getter/setter methods manually for my zfield. Plz let me know if I am missing anything. Your help will be greatly appreciated.
    Below is my requirement:
    I need to add an additional column (zfield) to a tree view. The name of the component is BTRESTREE. (there is only one view in this component- this view is having only one context node).
    I tried adding my zfield to the attributes (of the context node) through the wizard by right clicking on the 'Attributes'. But I am not getting the 'Create' Option.
    I posted a thread few days back regarding the same problem. One of the experts (Vikash Krishna) suggested me to add some my zfield by redefining the 'GET_TABLE_LINE_SAMPLE' method. As per his suggestion, I was finally able to see my zfield in
    the configuation tab.
    Now, I have to change the properties of my zfield (make this column editable) in the tree view. For that, the only option that I can see is to change the get_i_zfield( ) method (here we have 'rv_disabled') for my zfield. For this, first I need to add my zfield to the Attributes. To achieve this, I added getter/setter methods manually in the Proxy class.
    Thanks
    Raj

  • Do Get-Set methods break encapsulation?

    Some of my mates, who have been programming more time than me, say tha if you have a private variable which is accesible v�a two public methods "get" and "set" this breaks the encapsulation principle, and is equivalent to do the variable public, as anybody can read or modigy thge variable.
    I disagree, I think that two public get set methods still hide the implementation, you can acces directly to the variable, and so don't break the encapsulation principle.
    Can anybody tell me if I or them are right?

    As everybody else in the thread has indicated, accessors do not
    necessarily break encapsulation. However, I do not think the situation is as
    cut and dried as everybody seems to be making out.
    Accessors (by definition?) provide a mechanism to safely modify the member data of an object. Generally accessors match 1:1 the member data of an object (at least initially). By looking at accessors it is generally possible to make some good guesses about what member data an object contains. Which is a Bad Thing(TM). Of course, over time, accessors may reflect underlying implementation less and less accurately (which is when they become useful).
    Many years ago when I started OO programming, most "accepted" wisdom was that methods should represent object behaviour. For this reason, accessors were generally deemed to be a bad thing, and led to poorly encapsulated objects (since they do not really model behaviour; if you fill your car's petrol tank with petrol (gas? :>), "car.fillTank()" is preferred to
    "car.setCurrentTankVolume(car.getMaxTankCapacity())" in this mindset.
    The first defines object behaviour, and is safe, the second uses accessors to perform the same task (and is also pretty safe, but far less expressive).
    Generally I'd avoid accessors if only on the argument of them making code less clear and self-documenting, but that's a personal viewpoint.
    Another way to look at it is that accessors as most people view them are implemented after the member data has been defined; I prefer to break my object behaviour down first, define methods, and then define member data as needed to support the behaviour my object will exhibit.
    I certainly use accessors; a bank balance object is highly likely to have a "getBalance()" method. It's less likely to have a "setBalance()" object (very few people ever go into a bank and "set their balance". They always "make deposits" or "make withdrawals". They do, however, often "get their balance"). But my member data is derived from the object behaviour (including these "accessors") rather than vice versa. Are these "accessors" still "accessors"? A "setBalance()" method might be useful if the balance object is stored in a database so the database layer can populate it - but this is a design decision that should be taken in a measured way rather than "I have a balance member, let's add accessors".
    My guess is you would say "yes", whereas your friends would say "no"!

  • Getter/setter methods -- how do I use the return values

    I'm just learning Java, and I haven't been to this site since the end of July, I think. I have a question regarding getter and setter methods. I switched to the book Head First Java after a poster here recommended it. I'm only about a hundred pages into the book, so the code I'm submitting here reflects that. It's the beginnings of a program I'd eventually like to complete that will take the entered information of my CD's and alphabetize them according to whatever criteria I (or any user for that matter) choose. I realize that this is just the very beginning, and I don't expect to have the complete program completed any time soon -- it's my long term goal, but I thought I could take what I'm learning in the book and put it to practical use as I go along (or at lest try to).
    Yes I could have this already done it Excel, but where's the fun and challenge in that? :) Here's the code:
    // This program allows the user to enter CD information - Artist name, album title, and year of release -- and then organizes it according the the user's choice according to the user's criteria -- either by artist name, then title, then year of release, or by any other order according to the user's choice.
    //First, the class CDList is created, along with the necessary variables.
    class CDList{
         private String artistName;//only one string for the artist name -- including spaces.
         private String albumTitle;//only one string the title name -- including spaces.
         private int yearOfRelease;
         private String recordLabel;
         public void setArtistName(String artist){
         artistName = artist;
         public void setAlbumTitle(String album){
         albumTitle = album;
         public void setYearOfRelease(int yor){
         yearOfRelease = yor;
         public void setLabel(String label){
         recordLabel = label;
         public String getArtistName(){
         return artistName;
         public String getAlbumTitle(){
         return albumTitle;
         public int getYearOfRelease(){
         return yearOfRelease;
        public String getLabel(){
        return recordLabel;
    void printout () {
           System.out.println ("Artist Name: " + getArtistName());
           System.out.println ("Album Title: " + getAlbumTitle());
           System.out.println ("Year of Release: " + getYearOfRelease());
           System.out.println ("Record Label: " + getLabel());
           System.out.println ();
    import static java.lang.System.out;
    import java.util.Scanner;
    class CDListTestDrive {
         public static void main( String[] args ) {
              Scanner s=new Scanner(System.in);
              CDList[] Record = new CDList[4];
              int x=0;     
              while (x<4) {
              Record[x]=new CDList();
              out.println ("Artist Name: ");
              String artist = s.nextLine();
              Record[x].setArtistName(artist);
              out.println ("Album Title: ");
              String album = s.nextLine();
              Record[x].setAlbumTitle(album);
              out.println ("Year of Release: ");
              int yor= s.nextInt();
                    s.nextLine();
              Record[x].setYearOfRelease(yor);
              out.println ("Record Label: ");
              String label = s.nextLine();
              Record[x].setLabel(label);
              System.out.println();
              x=x+1;//moves to next CDList object;
              x=0;
              while (x<4) {
              Record[x].getArtistName();
              Record[x].getAlbumTitle();
              Record[x].getYearOfRelease();
              Record[x].getLabel();
              Record[x].printout();
              x=x+1;
                   out.println("Enter a Record Number: ");
                   x=s.nextInt();
                   x=x-1;
                   Record[x].getArtistName();
                Record[x].getAlbumTitle();
                Record[x].getYearOfRelease();
                Record[x].getLabel();
                Record[x].printout();
         }//end main
    }//end class          First, I'd like to ask anyone out there to see if I could have written this any more efficiently, with the understanding that I'm only one hundred pages into the book, and I've only gotten as far as getter and setter methods, instance variables, objects and methods. The scanner feature I got from another book, but I abandoned it in favor of HFJ.
    Secondly --
    I'm confused about getter and setter methods -- I'd like someone to explain to me what they are used for exactly and the difference between the two. I have a general idea, that getters get a result from the method and setters set or maybe assign a value to variable. I submitted this code on another site, and one of the responders told me I wasn't using the returned values from the getter methods (he also told me about using a constructor method, but I haven't got that far in the book yet.). The program compiles and runs fine, but I can't seem to figure out how I'm not using the returned values from the getter methods. Please help and if you can explain in 'beginners terms,' with any code examples you think are appropriate. It will be greatly appreciated.
    By the way, I'm not a professional programmer -- I'm learning Java because of the intellectual exercise and the fun of it. So please keep that in mind as well.
    Edited by: Straitsfan on Sep 29, 2009 2:03 PM

    Straitsfan wrote:
    First, I'd like to ask anyone out there to see if I could have written this any more efficiently, with the understanding that I'm only one hundred pages into the book, and I've only gotten as far as getter and setter methods, instance variables, objects and methods. The scanner feature I got from another book, but I abandoned it in favor of HFJ.Yes, there is tons you could have done more efficiently. But this is something every new programmer goes through, and I will not spoil the fun. You see, in 3 to 6 months when you have learned much more Java, assuming you stick with it, you will look back at this and be like "what the hell was I thinking" and then realize just haw far you have come. So enjoy that moment and don't spoil it now by asking for what could have been better/ more efficient. If it works it works, just be happy it works.
    Straitsfan wrote:
    Secondly --
    I'm confused about getter and setter methods -- I'd like someone to explain to me what they are used for exactly and the difference between the two. I have a general idea, that getters get a result from the method and setters set or maybe assign a value to variable. I submitted this code on another site, and one of the responders told me I wasn't using the returned values from the getter methods (he also told me about using a constructor method, but I haven't got that far in the book yet.). The program compiles and runs fine, but I can't seem to figure out how I'm not using the returned values from the getter methods. Please help and if you can explain in 'beginners terms,' with any code examples you think are appropriate. It will be greatly appreciated.
    By the way, I'm not a professional programmer -- I'm learning Java because of the intellectual exercise and the fun of it. So please keep that in mind as well.First, if you posted this somewhere else you should link to that post, it is good you at least said you did, but doubleposting is considered very rude because what inevitably happens in many cases is the responses are weighed against each other. So you are basically setting anyone up who responds to the post for a trap that could make them look bad when you double post.
    You are setting you getters and setters up right as far as I can tell. Which tells me that I think you grasp that a getter lets another class get the variables data, and a setter lets another class set the data. One thing, be sure to use the full variable name so you should have setRecordLabel() and getRecodLabel() as opposed to setLabel() and getLabel(). Think about what happens if you go back and add a label field to the CDList class, bad things the way you have it currently. Sometimes shortcuts are not your friend.
    And yes, you are using the getters all wrong since you are not saving off what they return, frankly I am suprised it compiles. It works because you don't really need to use the getters where you have them since the CDList Record (should be lowercase R by the way) object already knows the data and uses it in the printout() method. Basically what you are doing in lines like:
    Record[x].getArtistName();is asking for the ArtistName in Record[x] and then getting the name and just dropping it on the floor. You need to store it in something if you want to keep it, like:
    String artistName = Record[x].getArtistName();See how that works?
    Hope this helped, keep up the good learning and good luck.
    JSG

  • How to generate dynemic GET/SET Method in Struts.....

    hi,
    experts,
    i m doing struts application and i get struct at generatting GET/SET properties for my Dynemic html form in that form i fetch control name and related properties from database and i want to access this properties in action with the help of form which generates dynemic GET/SET properties depends on form controls
    how would i do please give some hints...
    example:
    my html form:
    <html:text name="bpmAttrForm" property="attrName"></html:text>
    . dynemic controls( i don't no how many )
    my form in struts
    public void getX()
    public void setX()
    .... dynemic GET/SET Properties ( i don't no how many )
    like this....
    thnks.....

    Hi ,
    You would have to create a Dynamic form class extending DynaActionForm and ovrride get and set method. In the implementation you access the dyanValues HashMap of DyanActionForm to set and get values from it.
    package yourpackage;
    import org.apache.struts.action.DynaActionForm;
    public class DynaForm extends DynaActionForm
      public Object get(String name)
          Object value = dynaValues.get(name);
          return (value);
      public void set(String name, Object value)
          dynaValues.put(name, value);
    }now in your struts configuration would be
    <form-bean name="myDynaForm" type="yourpackage.DynaForm" />
    if your action class execute method you would have to add and retrive your form properties through the map.
    DynaActionForm myDynaForm = (DynaActionForm) form;
    String prop1  = (String)myDyanaForm .get(propertyName);in your jsp you can access properties using expression library
    ${myDynaForm.map.propertyName}
    Cheers
    Masood

  • Accesing non get/set methods

    Is there a way to access non-get Collection methods from within JSTL tags? For example,
    <c:set var="size" value="${list.size()}" />

    There isn't a way to access non-bean methods like that. There are some workarounds. Counter-example for yours:
    <c:set var="size" value="${fn:length(list)}" />using the Function JSTL library. You can create your own function library or wrap the collection into a Bean to access those non-bean properties.

  • How to determine the get/set methods of an element from the schema

    Is there a way that I can obtain the java method call to an element using only the schema (maybe using SchemaTypeSystem, SchemaType, SchemaComponent)? For instance, as I traverse the schema is there a method that I can call that will return:
    "getPurchaseOrder().getCustomer().getName()"
    for the name element in the form of a string or some other representation?
    Thanks in advance.
    Joey

    Sorry Manoj,
    but i didn´t find out, why these programs should be able to solve my issue. They just display a picture using the CL_GUI_PICTURE control.
    I am looking fo a way to resize a given control to the very maximum, so that it fills the whole SAPGUI window!
    Thanks anyway...
    MIKE

  • Property name to getter / setter method translator

    Hi. I am to write a simple engine, that processes some method invocations on a java bean. When I see
    someBean.time < 0I am to replace that to look like this
    someBean.getTime() < 0Is there an automatic way of doing that? Is there a class in the API that has a static method like translateToMethod(String propertyName) or similar? Or do I have to do it myself?
    Thanks.

    I am not sure what you are looking for there--time will never be less than 0, unless you define it to be. If you are going to work with time, then look at the Calendar class.

  • NEWBIE --Get/Set methods HOW??

    I am not understanding what I am doing wrong. I added a variable getName and setname and i got errors. Can someone help??
    //=============================================================================
    //Paul Cote, Jr.
    //Java Programming
    //Fall 2006
    //Programming Project 4.2 PAGE 203
    // Design and implement a class call Dog that contains instance data that
    //represents the dog's name and age. Define the Dog constructior to accept and
    //initiate instance data. Include a method to compute and return the age of
    //the dog in 'person years'(seven times the dog's age). Include a toString
    //method that returns a one-line description of the dog. Create a driver
    //class called Kennel, whose main method instantiates and updates
    //several Dog objects.
    //============================================================================
    import java.util.Scanner;
    class Dog{
         public static void main(String[] args) {
         //info about the dog
         int age;
         String setname;
         String name;
    //public setname()
    //          return name;
         String message;
         Scanner scan=new Scanner(System.in);     
         System.out.println("Enter Dog's Name: ");
         name=scan.nextLine();
         System.out.println("Enter Dog's Age: ");
         age=scan.nextInt();
         System.out.println( "Your dog's name is " +name);
         System.out.println( name+" is "+ age+ " years old.");
         int HumanAge=(age*7);
         System.out.println( name+" is "+ HumanAge+ " human years old.");
    }

    you kinda missed the point buddy;
    import java.util.Scanner;
    class Dog{
    private int age;
    private String name;
    public Dog() {
    //info about the dog
    age = 0; //any default value will do
    name = ""; //any default value will do
    public void setName(String s) {
    this.name = s;
    public String getName() {
    return this.name;
    public static void main(String args[]) {
    String message;
    Scanner scan=new Scanner(System.in);
    System.out.println("Enter Dog's Name: ");
    setName(scan.nextLine());
    System.out.println("Enter Dog's Age: ");
    setAge(scan.nextInt());
    System.out.println( "Your dog's name is " + getName());
    System.out.println( name+" is "+ getAge()+ " years old.");
    int HumanAge=(getAge()*7);
    System.out.println( getName()+" is "+ HumanAge+ " human years old.");
    public static void main(String[] args) {
    }

  • Using getter/setter for returing a string variable to display on an Applet

    have two classes called, class A and class testA.
    class A contains an instance variable called title and one getter & setter method. class A as follow.
    public class A extends Applet implements Runnable, KeyListener
         //Use setter and getter of the instance variable
         private String title;
         public void init()
              ASpriteFactory spriteFactory = ASpriteFactory.getSingleton();
              // Find the size of the screen .
              Dimension theDimension = getSize();
              width = theDimension.width;
              height = theDimension.height;
              //Create new ship
              ship = spriteFactory.createNewShip();
              fwdThruster = spriteFactory.createForwardThruster();
              revThruster = spriteFactory.createReverseThruster();
              ufo = spriteFactory.createUfo();
              missile = spriteFactory.createMissile();
              generateStars();
              generatePhotons();
              generateAsteroids();
              generateExplosions();
              initializeFonts();
              initializeGameData();
              //Example from Instructor
              //setMyControlPanel( new MyControlPanel(this) );
              // new for JDK 1.2.2
              addKeyListener(this);
              requestFocus();
         public void update(Graphics theGraphics)
              // Create the offscreen graphics context, if no good one exists.
              if (offGraphics == null || width != offDimension.width || height != offDimension.height)
                   // This better be the same as when the game was started
                   offDimension = getSize();
                   offImage = createImage(offDimension.width, offDimension.height);
                   offGraphics = offImage.getGraphics();
                   offGraphics.setFont(font);
              displayStars();
              displayPhotons();
              displayMissile();
              displayAsteroids();
              displayUfo();
              //displayShip();
              //Load the game with different color of the space ship          
              displayNewShip();
              displayExplosions();
              displayStatus();
              displayInfoScreen();
              // Copy the off screen buffer to the screen.
              theGraphics.drawImage(offImage, 0, 0, this);
         private void displayInfoScreen()
              String message;
              if (!playing)
                   offGraphics.setColor(Color.white);
                   offGraphics.drawString("\'A\' to Change Font Attribute", 25, 35);
                   offGraphics.drawString(getTitle(), (width - fontMetrics.stringWidth(message)) / 2, height / 2
                             - fontHeight);
                   message = "The Training Mission";
                   offGraphics.drawString(message, (width - fontMetrics.stringWidth(message)) / 2, height / 2);
                   message = "Name of Author";
                   offGraphics.drawString(message, (width - fontMetrics.stringWidth(message)) / 2, height / 2
                             + fontHeight);
                   message = "Original Copyright 1998-1999 by Mike Hall";
                   offGraphics.drawString(message, (width - fontMetrics.stringWidth(message)) / 2, height / 2
                             + (fontHeight * 2));
                   if (!loaded)
                        message = "Loading sounds...";
                        int barWidth = 4 * fontWidth + fontMetrics.stringWidth(message);
                        int barHeight = fontHeight;
                        int startX = (width - barWidth) / 2;
                        int startY = 3 * height / 4 - fontMetrics.getMaxAscent();
                        offGraphics.setColor(Color.black);
                        offGraphics.fillRect(startX, startY, barWidth, barHeight);
                        offGraphics.setColor(Color.gray);
                        if (clipTotal > 0)
                             offGraphics.fillRect(startX, startY, (barWidth * clipsLoaded / clipTotal), barHeight);
                        offGraphics.setColor(Color.white);
                        offGraphics.drawRect(startX, startY, barWidth, barHeight);
                        offGraphics
                                  .drawString(message, startX + 2 * fontWidth, startY + fontMetrics.getMaxAscent());
                   else
                        message = "Game Over";
                        offGraphics.drawString(message, (width - fontMetrics.stringWidth(message)) / 2, height / 4);
                        message = "'S' to Start";
                        offGraphics.drawString(message, (width - fontMetrics.stringWidth(message)) / 2, height / 4
                                  + fontHeight);
              else if (paused)
                   offGraphics.setColor(Color.white);
                   message = "Game Paused";
                   offGraphics.drawString(message, (width - fontMetrics.stringWidth(message)) / 2, height / 4);
         public String getTitle() {
              System.out.print(title);
              return title;
         public void setTitle(String title) {
              this.title = title;
    }displayInfoScreen method in class A calls out for getTitle( ) to be displayed on an applet as an initial display string for the application.
    The instance variable title is set by setTitle method which is called out in class testA as follow,
    public class testA extends TestCase
          * testASprite constructor comment.
          * @param name
          *          java.lang.String
         public testA(String name)
              super(name);
          * Insert the method's description here.
          * @param args
          *          java.lang.String[]
         public static void main(String[] args)
              junit.textui.TestRunner.run(suite());
              // need to figure out how to get rid of the frame in this test
              System.exit(0);
         public static Test suite()
              return new TestSuite(testA.class);
          * Basic create and simple checks
         public void testCreate()
              A theGame = new A();
              assertNotNull("game was null!", theGame);
          * Basic create and simple checks
         public void testInit()
              A theGame = new A();
              Frame gameFrame = new Frame("THE GAME");
              gameFrame.add(theGame);
              int width = 640;
              int height = 480;
              gameFrame.setSize(width, height);
              // must pack to get graphics peer
              gameFrame.pack();
              theGame.resize(width, height);
              theGame.setTitle("TEST THE GAME");
              theGame.init();
              assertEquals("ASprite width not set", A.width, width);
              gameFrame.dispose();
              gameFrame.remove(theGame);
    }Basically, class testA invokes the init( ) method in class A and start the applet application. However, it displays a white blank display. If I change the getTitle( ) in the displayInfoScreen method to a fixed string, it works fine. Did I forget anything as far as using getter & setter method? Do I have to specify some type of handle to sync between setter and getter between two classes? Any feedback will be greatly appreciated.
    Thanks.

    Your class A extends runnable which leads me to believe that this is a multi-threaded application. In that case, title may or may not be a shared variable. Who knows? It's impossible to tell from what you posted.
    Anyway, what is happening is that your applet is being painted by the JFrame before setTitle is called. After that, who knows what's happening. It's a complicated application. I suspect that if you called setTitle before you added the applet to the frame, it would work.

  • Setter method not getitng called in the custom tag

    Hi,
    I have written a custom tag and I have declared an attribute in the tld file and have specified the setter method for the same in the java tag file but that setter method is not getting called...for rest of the attributes, the methods are getting called and not just for one!! any idea what could be the problem....
    Regards
    Deepak Saini

    Do you have a getter method to match that property?
    Post some example code - what does your tld define for this property, and what get/set methods have you defined for it?

  • Set Methods v/s Vector

    Hello,
    In my Java Program, I have a doubt.
    I have 2 set methods, setName(string) and setData(int)
    Eg:
    Name = A
    Data (for A) = 12, 14, 20, 22
    I am having a 'Vector of Array' for storing the data, where each position of the Vector will contain an array. From the Eg., Assume....A will be stored as the 0th element of the array in the 2nd position of the vector. A will be followed by the data items which will occupy the array from the 1st element onwards.
    With respect to the Bean Standards, I can have only one parameter passed into a set method. I am not able to understand how do I add the name and the data inside the Vector. Where exactly should I call my 'addData(String, int)' method?
    Since setName() and setData() come in the 'Properties Window', I am unable to understand how to add the data in the vector. The properties change when there is a 'lost focus', so the method gets called even if either is entered. Whereas, I need the 'Name' and the 'Data' to go into the Vector together.
    Waiting for reply
    Thanks

    In this case directly call the function name and pass the arguments..The get set methods sometimes do not behave properly
    Hello,
    In my Java Program, I have a doubt.
    I have 2 set methods, setName(string) and
    setData(int)
    Eg:
    Name = A
    Data (for A) = 12, 14, 20, 22
    I am having a 'Vector of Array' for storing the data,
    where each position of the Vector will contain an
    array. From the Eg., Assume....A will be stored as
    the 0th element of the array in the 2nd position of
    the vector. A will be followed by the data items which
    will occupy the array from the 1st element onwards.
    With respect to the Bean Standards, I can have only
    one parameter passed into a set method. I am not able
    to understand how do I add the name and the data
    inside the Vector. Where exactly should I call my
    'addData(String, int)' method?
    Since setName() and setData() come in the 'Properties
    Window', I am unable to understand how to add the data
    in the vector. The properties change when there is a
    'lost focus', so the method gets called even if either
    is entered. Whereas, I need the 'Name' and the 'Data'
    to go into the Vector together.
    Waiting for reply
    Thanks

  • Please help- How can I publish an object with irregular getter/setter metho

    I'm encountering a problem with weblogic 9.2 web service. Here it is the description:
    I have a java class which doesn't expose getter/setter method, Like this:
    public class MyEntityList
    implements Cloneable, Serializable
    private Map subEntityMap;
    public final Object[] toArray()
    return subEntityMap.values().toArray();
    public final Iterator subEntities()
    return subEntityMap.values().iterator();
    public final GFIBaseSubEntity getSubEntityByKey(String key)
    if(key == null)
    return null;
    else
    return (GFIBaseSubEntity)subEntityMap.get(key);
    public final void setSubEntity(GFIBaseSubEntity entity)
    subEntityMap.put(entity.getKey(), entity);
    When I publish this object out, the web service engine will not parse the value in this object for it hasn't getter methods. But I do need the value in it, and I can't change the class for it's from external system. Can I define my own serializer class to process the MyEntityListin weblogic 9 or 10? Or is there any way to process this case?
    Thanks in advance

    In 1.4 you have ImageIO available ... javax.imageio.ImageIO.write is the method to call.
    - David

Maybe you are looking for

  • Final Cut Pro X update from expired trial version

    Just bought Final Cut Pro X cannot open it I have an expired trial version from 2012-13. How do I move forward?

  • Where to find help with SQL Developer installation?

    Hi, I just want to try out SQL Developer and compare its capabilities to TOAD's. Unfortunately, I am not PC software savvy and now am stuck with a SQL Developer (sqldeveloper-1.2.2998) installation problem. When I clicked on the .exe file, I got a bl

  • Service Orders Collective Processing

    Hi all, I have 2 quick questions: - Is there any way where we can do the revaluation at actual prices for service orders? I tried using CON2, but it doesn't work - Suppose i am using valuated Sales Order Stock with control by SO, at which level shoul

  • Equivalent to ROLAP :insert, update, delete in OLAP DML?

    I have a ROLAP star schema. The process update is in Real Time using triggers in the operational tables. When an update in the operational table occur the trigger call a store procedure where : 1- find de fact row using dimensions key, 2-the messure

  • How to handle the maturity date of loan in FCR

    In Jilin, we have a contract maturity date and FCR maturity date, the contract maturity date can be less than or equal to the FCR maturity date. If the contract maturity date is less than the FCR maturity date, EFS will be done for the loan account i