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.

Similar Messages

  • Question about generics and subclassing

    Hi all,
    This has been bothering me for some time. It might be just me not understanding the whole thing, but stay with me ;):
    Suppose we have three classes Super, Sub1 and Sub2 where Sub1 extends Super and Sub2 extends Super. Suppose further we have a method in another class that accepts (for example) an AbstractList<Super>, because you wanted your method to operate on both types and decide at runtime which of either Sub1 or Sub2 we passed into the method.
    To demonstrate what I mean, look at the following code
    public class Super {
      public methodSuper() {
    public class Sub1 extends Super {
      public methodSub1() {
        // Do something sub1 specific
    public class Sub2 extends Super {
      public methodSub2() {
         // Do something sub2 specific
    public class Operate {
      public methodOperate(AbstractList<Super> list) {
        for (Super element : list) {
           // Impossible to access methods methodSub1() or methodSub2() here, because list only contains elements of Super!
           // The intention is accessing methods of Sub1 or Sub2, depending on whether this was a Sub1 or Sub2 instance (instanceof, typecasting)
    }The following two methods seem impossible:
    Typecasting, because of type erasure by the compiler
    Using the instanceof operator (should be possible by using <? extends Super>, but this did not seem to work.
    My question now is: How to implement passing a generic type such as AbstractList<Super> while still making the methods of Sub1 and Sub2 available at runtime? Did I understand something incorrectly?

    malcolmmc wrote:
    Well a List<Super> can contain elements of any subclass of super and, having obtained them from the list, you could use instanceof and typecast as usual.I agree with you on this one, I tested it and this simply works.
    Of course it would be better to have a method in Super with appropriate implementations in the subclasses rather than use distinct method signatures, instanceof and casting isn't an elegant solution. Alternatively use a visitor pattern.Not always, suppose the two classes have some similarities, but also some different attributes. Some getters and setters would have different names (the ones having the same name should be in the superclass!). You want to be able to operate on one or the other.
    Generics doesn't make much difference here, exception it would be more flexible to declare
    public methodOperate(AbstractList<? extends Super> list) {Which would alow any of AbstractList<Super>, AbstractList<Sub1> or AbstractList<Sub2> to be passed.I tried it and this also works for me, but I am still very, very confused about why the following compiles, and gives the result below:
    public class Main {
         public static void main( String[] args ) {
              AbstractList<Super> testSub = new ArrayList<Super>();
              testSub.add( new Sub1( "sub1a" ) );
              testSub.add( new Sub1( "sub1b" ) );
              accept( testSub );
         private static void accept( AbstractList<? extends Super> list ) {
              for ( int i = 0; i < list.size(); i++ ) {
                   Super s = list.get( i );
                   System.out.println( s.overrideThis() );
    public class Sub1 extends Super {
         private String sub1;
         public Sub1( String argSub1 ) {
              sub1 = argSub1;
         public String overrideThis() {
              return "overrideThis in Sub1";
         public String getSub1() {
              return sub1;
    public class Sub2 extends Super {
         private String sub2;
         public Sub2( String argSub2 ) {
              sub2 = argSub2;
         public String overrideThis() {
              return "overrideThis in Sub2";
         public String getSub2() {
              return sub2;
    public class Super {
         public Super() {
         public String overrideThis() {
              return "OverrideThis in Super";
    }With this output:
    overrideThis in Sub1
    overrideThis in Sub1Even using a cast to Super in Main:
    Super s = (Super) list.get( i );does not return the Sub1 as a Super (why not??)
    Sorry for the long code snippets. I definitely want to understand why this is the case.
    (Unwise, I thing, to use Super as a class name, too easy to get the case wrong).OK, but I used it just as an example.

  • [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

  • JSF Question about getters

    Hi all! I`ve made a simple page with one input text and submit button. I attached a managed bean to the page and getters and setters for the input. The bean looks like this:
    public class User {
         private String name;
         public User() {
         public String getName() {
              System.out.println("getName");
              return name;
         public void setName(String name) {
              this.name = name;
         public String act() {
              return null;
    }When i open the page in the browser the getter method is invoked once. When i click on the submit button the getter is invoked two times. So i get:
    getName
    getName
    getName
    Why the jsf invokes the getter two times after submit?

    You have to learn about lifecycle.
    http://www.developertutorials.com/tutorials/java/jsp-application-lifecycle-050504/page14.html
    JSF for Nonbelievers: The JSF Application Lifecycle - Immediate Event Handling

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

  • 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}" />

  • A question about grub and USB

    Hi All
    I have a quick question about grub and USB that I can't quite find the answer to by searching.   Most of the FAQs discuss booting a full linux dristribution from USB. My situation is this.  I am getting a new computer with two drives, the second will be arch and the first will be Vista (for my wife).  I want the computer to boot the same way that my wife's machine boots at work so I don't want to install grub on the MBR.  So, is there a way to have all of the grub config files and kernels installed on the second drive and simply install to grub boot loader to the MBR of a USB stick?  My goal would be to simply plug the USB stick into the new PC and boot arch from the second drive. 
    Thanks
    Kev

    i cant say for hp's
    havent worked on any in a while
    recent machines have been coupleof dell's , vaio & emachine
    which dells do offer it at least the ones i tried , my laptop does(dell)
    all home pc's are built by me which do offer to boot individual drives
    what hp you getting it may tell in specs
    are both discs sata? if so it might not offer this option with 2 drives of same interface
    check your power supply alot of these preconfigured machines put cheap under reated power supplies in there
    & will burn your motherboard i just replaced PS(250 watt) & mobo(845gvsr) in an emachines <cheap stuff<
    i hope you researched the pc before buying ie : mobo, power supply are the biggest concerns
    i find it much more benificial to build my own machine gives me peace at mind. the cost is sometimes more in $ but not always , your biggest expense is time researching hardware
    if you live in usa the best places to start looking are bensbargains.net & pricewatch.com
    i am not affiliated with either & niether sell the hardware they are just advertisers a place to buy
    for costomized machines that i would trust is unitedmicro.com theyll asemble & test before shipping
    i have gotten 2 machines so far from them with NO PROBLEMS with hardware (knock knock)
    you may want to consider this in your next venture for pc

  • I have a Macbook Pro june 2011... I have 8GB ram but I only have 256mb VRAM... I've read some other questions about this and I realized... Why do I not have 560mb of VRAM since I have 8GB of RAM? Is there any way to get more VRAM to play games on steam?

    I have a Macbook Pro june 2011... I have 8GB ram but I only have 256mb VRAM...
    I've read some other questions about this and I realized... Why do I not have 560mb of VRAM since I have 8GB of RAM?
    Is there any way to get more VRAM to play games on steam?
    I've learned  by reading other topics that I can't upgrade my graphics card on my Macbook Pro because it's soldered into the motherboard or somthing like that, but please tell me if there is any way to get more video ram by chaning some setting or upgrading something else. I'd also like to know why I only have 256MB of VRAM when I have 8GB of RAM, since I have 8GB of RAM I thought I was supposed to have 560mb of VRAM...
    So the two questions are...
    Is there any way to upgrade my VRAM, so that I can play games on steam?
    Why do I only have 256MB VRAM when I have 8GB total RAM?
    Other Info:
    I have a quad core i7 Processor.
    My graphcics card is the AMD Radeon HD 6490M.
    I am also trying to play games on my BOOTCAMPed side of my mac, or my Windows 7 Professional side.
    THANK YOU SO MUCH IF YOU CAN REPLY,
    Dylan

    The only two items that a user can change on a MBP are the RAM and HDD (Retinas not included).  You have what the unit came with and the only way you will be able to change that is to purchase a MBP with superior graphics
    If you are very much into gaming, the I suggest A PC.  They are far superior for that type of application to a MBP.
    Ciao.

  • A few questions about MacBooks and Parallels Desktop.

    I have a few questions about MacBooks and Parallels Desktop.
    1) I understand I need at least 1GB of RAM to run Parallels Desktop but what about the hard drive, is the stock 60GB drive big enough?
    2) Related to question 1, even if it was big enough to allow me to install and run Windows would the 60GB drive be enough if I wanted to install a Linux distribution as well?
    3) This has nothing to do with Parallels Desktop but thought I'd ask it here anyway, do Apple Stores carry just the stock MacBooks, or do they carry other configurations?
    Thanks
    Keith

    1. Depend on how intensive you use that HD for saving data on both Mac OS and XP. For standard installation on both OS X and XP, the space of 60 Gb is enough.
    2. Same answer as no 1. You can install all three on that HD space, but the extra spacce available will be less and less for your data. You can save your data on external or back up on cd/dvd and erase it from the HD to keep the free space.
    Remember to leave at least 2 or 3 Gb for virtual memory usage.
    3. Just call them, maybe they don't have it in store stock, but by appointment they might configure one for you before your pick-up date.
    Good Luck

  • One question about Pricing and Conditions puzzle me for a long time!

    One question about Pricing and Conditions puzzle me for a long time.I take one example to explain my question:
    1-First,my sale order use pricing procedure RVAA01.
    2-Next,the pricing procedure RVAA01 have some condition type,such as EK01(Actual Costs),PR00(Price)....,and so on.
    3-Next,the condition type PR00 define the Access Sequences PR00 as it's Access Sequences.
    4-Next,the Access Sequences PR00 have some Condition tables,such as:
         table 118 : "Empties" Prices (Material-Dependent)
         table 5 : Customer/Material
         table 6 : Price List Type/Currency/Material
         table 4 : Material
    5-Next,I need to maintain Condition tables's Records.Such as the table 5(Customer/Material).I guess the sap would supply one screen for me to input the data of table 5.At this screen,the sap would ask me to select one table,such as table 5.When I select the table 5,the sap would go to the screen to let me input the data of table 5.But when I use the T-CODE VK31 or VK32 to maintain Condition tables's Record,I found it's total different from my guess:
    A-First,I can not found one place for me to open the table,such as table 5,to let me input the data?
    B-Second,For example,when I select the VK31->Discounts/Surcharges->By Customer/Material,the sap show the grid view at the right side.At the each line of the grid view,you need to select the Condition Type at the first field.And this make me confused very much.Why the sap need me to select one Condition Type but not the Condition table?To the normal logic,it ought not to select Condition table but not the Condition Type!
    Dear all,I'm a new one in sd.May be this is a very stupid question.But it did puzzle me for a long time.If any one can  explain this question in detail and let me understand the concept,I will appreciate him/her very much.Thank you.

    Hi,
    You said that you are using the T.codes VK31 or VK32.
    These transaction codes are used to enter condition records for standard condition types. As you can see a grid left side having all the standard condition types like price, discounts, taxes, frieghts.
    Pl check using T.code VK11 OR VK12 (change mode)
    Here you can enter the required condition type, in the intial screen. (like PR00, MWST, K004, K005 .....etc)
    After giving the condition type, press enter or click on Combinations icon on top of the screen. Then you can see all the condition tables which you maintained for that condition type. Like as you said table 118, table 5, table 6 and table 4.
    You can select any table and press enter, then you can go into the screen in which you have all the field cataglogues you maintained for that table. For example you selected combination of Customer/Material (table 5) then after you press enter then you can see customer field on top, and material fields.
    You can give all the required values and save the conditon record.
    Hope this is clear.
    REWARD IF HELPFUL.
    Regards,
    praveen

  • Question about Struts and ActionForm

    Hi,
    I've a LoginForm class that extends ActionForm and the login.jsp page accepts 2 fields - "username" and "password" and there are corresponding setters and getters in LoginForm.java. As part of moving this to container managed security (using login modules), I want to change the field names to j_username and j_security. I made the change to the login.jsp page and also to the getters and setters (made them getJ_username, getJ_password) but I keep getting the "getter is not defined" struts related error. any thoughts?

    You would need to follow naming convention. It should be
    userName,
    I never tried with underscore, try j_userName (caps N). I don't think it will work.

  • 2 question about GPU and Lens correction ,cs5

    Hi
    i have 2 questions about Gpu and lens correction in Cs5
    1)Filter->lens correction->search online
    i get often and almost every connection time out at the first click on search online , at the second click i get no online profile
    is it normal?
    2) question is about Gpu
    it run faster , but talking about ajustament layer
    like saturation or vibrance for example
    i found with the gpu on , a light slow refresh compared with gpu off
    i have set cache  levels 6 ,history 20
    i guess are the defaul
    well i add a saturation layer and move the saturation slide ,increase o decrease saturation
    with Gpu Off , the changes are immedially , i mean i can see in real time the increase o decrease of saturation
    with Gpu On it takes a few(very few) time more
    again is normal ?
    don't be angry , i'm going to buy cs5 and i'm unsecure ... the price make a big role
    thanks

    For what it's worth, I also see a timeout on the first [ Search Online ] click, after about half a minute delay.  Second click turns up results immediately.  This happens each time Lens Correction is started, even without restarting Photoshop, and in both 32 and 64 bit versions.  Also note that I started with one profile listed by default (though from the wrong camera) for my 40D with 28-135 zoom.
    I alsow noticed that I was seeing progress bar activity in the Lens Correction dialog while I was typing this (even though Lens Correction was NOT the active window) every time I hit the 'L' key.  Strange.
    Windows 7 x64.
    -Noel

  • Three questions about Java and Ftp

    Hello, i've the following questions about Java and Ftp:
    1- .netrc file is in $HOME directory but i can't access to this directory from java code. The following line producesan Exception (directory doesn't exists)
    FileWriter file = new FileWriter ("$HOME/.netrc");
    2- .netrc file must have the following permissions: -rw- --- --- but when i create the .netrc file the following permissions are on default: -rw- r-- r--, how can i change this permissions? (In java code, i can't use chmod.....)
    3- Are there any way to pass parameters to a .netrc file? If i get to do this i needn't change the permissions because i can't modify or create/destroy this file.
    Thanks in advanced!!!
    Kike

    1- .netrc file is in $HOME directory but i can't
    access to this directory from java code. The
    following line producesan Exception (directory
    doesn't exists)
    FileWriter file = new FileWriter ("$HOME/.netrc");$HOME would have to be replaced by a shell, I don't
    think you can use it as part of a legal path.
    Instead, use System.getProperty("user.home");
    Ok, thanks
    2- .netrc file must have the followingpermissions:
    -rw- --- --- but when i create the .netrc file the
    following permissions are on default: -rw- r--r--,
    how can i change this permissions? (In java code,i
    can't use chmod.....)Yes, you can: Runtime.exec("chmod ...");
    I need to use estrictly the .netrc with -rw- --- --- permissions
    Yes, i can use Runtime.exec ("chmod ..."); but i don't like very much this solution because is a slow solution, am i right?
    3- Are there any way to pass parameters to a.netrc
    file? If i get to do this i needn't change the
    permissions because i can't modify orcreate/destroy
    this file.I don't think so. Why do you need the .netrc file in
    Java at all? Writing a GUI frontend?I want to use automatic ftp in a java program and FTP server, the files and path are not always the same, so i can:
    - modify .netrc (for me is the complex option)
    - destroy and create a new .netrc (is easier but i have permissions problem)
    - use .netrc with parameters but i haven't found any help about it
    Thanks for your prompt reply!!!!
    Kike

  • 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?

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

Maybe you are looking for