Accessor vs Mutator methods

Nowadays I'm studying for SCJP 5.0 and I found a strange definition about Encapsulation .
When I have seen the "Accessor methods"
To me, it would be related with the both "setters" and "getters" methods
But on a mock I found this definition:
"Accessor methods are used to read data members; mutator methods are used to set data members. The mutator methods can validate the parameter values before the values are used to change the state of the internal data model."
on the mock this sentence would be strong:
"Accessors methods are used to prevent fields from being set with invalid data."
the correct would be:
"Mutator methods are used to prevent fields from being set with invalid data."
In order to do the exam, how the Sun call that methods?
- setters and getter methods?
- Accessor methods and Mutator methods?
- or only Accessor methods for the both?
Message was edited by:
oalexandrino

I asked that question because I found the following one on the example of mock:
A class can not be called "tightly encapsulated" unless which of the following is true?
a.      All member fields are declared final.
b.      The class is not anonymous.
c.      The internal data model can be read and modified only through accessor and mutator methods.
d.      The class is an inner class.
e.      None of the above
I think it would be found in:
Section 5: OO Concepts
all right?

Similar Messages

  • Accessor and Mutator Methods

    I'm currently learning how to use different types of methods within my program.
    One of the things that I'm getting stuck on is how to get user input and then feed that into a new instance of the class that I made.
    Here is my cat class
    public class Cat
         private String name;
         private int age;
         private double weight;
         private String breed;
         private boolean declawed;
         private double percentGrowthRate;
         public void setName(String name)
              this.name = name;
         public void setAge(int age)
              this.age = age;
         public void setWeight(double weight)
              this.weight = weight;
         public void setBreed(String breed)
              this.breed = breed;
         public void setDeclawed(boolean declawed)
              this.declawed = declawed;
         public void setDeclawed() // This will get overloaded later
         public void Display()
              System.out.printf("Name: %s\n Age: %d\n Weight: %f\n Breed: %s\n Declawed: %b\n", this.name, this.age,
                   this.weight, this.breed, this.declawed);
    }And here is my Driver program
    import java.util.Scanner;
    public class CatDriver
         public static void main(String[] args)
              String catName = "";
              int catAge = 0;
              double catWeight = 0.0;
              String catBreed = "";
              boolean catDeclawed = false;
              Cat cat1, cat2, cat3;
              Scanner stdIn = new Scanner(System.in);
              System.out.print("Enter the name of your cat: ");
              catName = stdIn.nextLine();
              cat1 = new Cat(); // this is the part I'm having trouble with
              System.out.printf("How old is %s: ", catName);
              catAge = stdIn.nextInt();
              cat1.setAge(catAge);
              System.out.printf("How much does %s weigh: ", catName);
              catWeight = stdIn.nextDouble();
              cat1.setWeight(catWeight);
              System.out.printf("What breed of cat is %s: ", catName);
              catBreed = stdIn.nextLine();
              cat1.setBreed(catBreed);
              System.out.printf("Has %s been declawed: ", catName);
              catDeclawed = stdIn.nextBoolean();
              cat1.setDeclawed(catDeclawed);
              cat1.Display();
         } // end main
    } // end classWhat I tried doing first was saying
    Cat catName = new Cat();But that gave me an error and wouldn't work. So my first question is how do you get input from the user and then name an instance of a class after that input (I don't even know if I'm saying that right but hopefully someone understands ><). I want the user to enter the name Gus and then have it create a new instance of the Cat class called Gus.
    My second question is, when the code is compiled and run as is, I have some sort of format error when it gets time to ask me the cat's breed. I get asked for the breed AND the declawed on the same line and never have a chance to put in the breed. I can't see any reason why it would do this so anyone who could clear that up also would be appreciated.

    Alright. I think I see what you mean.
    System.out.print("Enter the name of your cat: ");
              catName = stdIn.nextLine();
              cat1.setName(catName);I added the last line there and now my output returns the name of the cat instead of null. Let me refine my question a little now.
    The program works perfectly if I only have 1 cat but let's say I want to enter 3 cats, or even have a loop that will let me enter as many cats as I want. Am I going to have to keep changing my cat variables
    Cat cat1, cat2, cat3;To include the number of cats that I expect to run through? I could do it that way and then just reproduce all the above code changing cat1 to cat2, cat3, etc. but it seems like there has to be a better way to do it.

  • Using mutator and accessor methods in main.

    Would somebody explain to me exactly how mutator and accessor methods make a class and it's driver program work together. I understand the principle of encapsulation, but I'm obviously missing something. I get the syntax, but what actually happens? I'm hoping a fresh perspective on it will help me understand better.
    I guess another way to ask the question could be: how do you use accessor and mutator methods in the main program that calls them?

    >
    the assignment says to have a
    "reasonable set of accessor and mutator methods
    whether or not you use them". So in my case I have
    them written in the class but do not call them inthe
    driver program. And like I said, the program does
    what it's supposed to do.This class you're in worries me. I'm sure what
    polytropos said is true: they're trying to make you
    think about reuse. But adding to an API without cause
    is widely considered to be a mistake, and there are
    those who are strongly opposed to accessors/mutators
    (or worse, direct field access) on OOP design grounds.The class is based on the book Java: Introduction to Computer Science and Progamming, by Walter Savitch. Until now I've been pretty happy with it. Another problem, to me anyway, is that so far we've done a few, cumulative programming projects per chapter. This time, there was one assignment for the whole chapter that is suppsoed to incorporate everything. But that's just me complaining.
    Here is the code I have and that it looks like I'll be turning in... criticisms welcome.
    Here is the class:
    public class GradeProgram//open class
         private double quiz1;
         private double quiz2;
         private double mid;
         private double fin;
         private double finalGrade;
         private char letterGrade;
         public void readInput()//open readInput object
              do
                   System.out.println("Enter the total points for quiz one.");
                   quiz1 = SavitchIn.readLineInt();
                   System.out.println("Enter the total points for quiz two.");
                   quiz2 = SavitchIn.readLineInt();
                   System.out.println("Enter the mid term score.");
                   mid = SavitchIn.readLineInt();
                   System.out.println("Enter final exam score.");
                   fin = SavitchIn.readLineInt();
                   if ((quiz1>10)||(quiz2>10)||(quiz1<0)||(quiz2<0))
                   System.out.println("Quiz scores are between one and ten.  Re-enter scores");
                   if ((mid>100)||(fin>100)||(mid<0)||(fin<0))
                   System.out.println("Exam scores are between zero and one hundred.  Re-enter scores.");
              while ((quiz1>10)||(quiz2>10)||(quiz1<0)||(quiz2<0)||(mid>100)||(fin>100)||(mid<0)||(fin<0));
         }//end readInput object
         public void output()//open output object
              System.out.println();
              System.out.println("You entered:");
              System.out.println("Quiz 1: " + (int)quiz1);
              System.out.println("Quiz 2: " + (int)quiz2);
              System.out.println("Mid term: " + (int)mid);
              System.out.println("Final exam: " + (int)fin);
              System.out.println();
              System.out.println("Final grade: " + (int)percent() + "%");
              System.out.println("Letter grade: " + letterGrade());
         }//end output object
         public void set(double newQuiz1, double newQuiz2, double newMid, double newFin, double newFinalGrade, char newLetterGrade)
              if ((newQuiz1 >= 0)&&(newQuiz1 <= 10))
              quiz1 = newQuiz1;
              else
                   System.out.println("Error: quiz scores are between zero and ten.");
                   System.exit(0);
              if ((newQuiz2 >= 0)&&(newQuiz2 <= 10))
              quiz2 = newQuiz2;
              else
                   System.out.println("Error: quiz scores are between zero and ten.");
                   System.exit(0);
              if ((newMid >= 0)&&(newMid <= 100))
              mid = newMid;
              else
                   System.out.println("Error: exam scores are between zero and one hundred.");
                   System.exit(0);
              if ((newFin >= 0)&&(newFin <= 100))
              fin = newFin;
              else
                   System.out.println("Error: exam scores are between zero and one hundred.");
                   System.exit(0);
              letterGrade = newLetterGrade;
         public double getQuiz1()
              return quiz1;
         public double getQuiz2()
              return quiz2;
         public double getMid()
              return mid;
         public double getFin()
              return fin;
         public char getLetterGrade()
              return letterGrade;
         private double finalPercent()//open finalPercent object
              double quizPercent = (((quiz1 + quiz2) /2) * 10) / 4;
              if (((((quiz1 + quiz2) /2) * 10) % 4) >= 5)
                   quizPercent++;
              double midPercent = mid / 4;
              if ((mid % 4) >= 5)
                   midPercent++;
              double finPercent = fin / 2;
              if ((fin % 2) >= 5)
                   finPercent++;
              finalGrade = (quizPercent + midPercent + finPercent);
              return (finalGrade);
         }//end final percent object
         private double percent()//open percent object - helping object
              double percentGrade = finalPercent();
              return (percentGrade);
         }//end percent object
         private char letterGrade()//open letterGrade object
              double letter = percent();
              if (letter >= 90)
                   return ('A');
              else if (letter >= 80)
                   return ('B');
              else if (letter >= 70)
                   return ('C');
              else if (letter >= 60)
                   return ('D');
              else
                   return ('F');
         }//end letterGrade object
         private double quizScore()//open quizScore object
              double quizes = ((quiz1 + quiz2) /2) * 10;
              return (quizes);
         }// close quizScore object
    }//end classAnd here is the driver program:
    public class GradeProgramDemo
         public static void main(String[] args)
              String cont;
              do
                   GradeProgram firstStudent = new GradeProgram();
                   firstStudent.readInput();
                   firstStudent.output();
                   System.out.println();
                   System.out.println("Enter more student grades?  Enter Y to continue");
                   System.out.println("or press enter to quit.");
                   cont = SavitchIn.readLine();
                   System.out.println();
              while (cont.equalsIgnoreCase("y"));

  • Constructor, accessor methods

    Hi,
    I have read some codes examples from book, one code made direct references to instance variables from inside client
    implementations (e.g., emp.employeeid) - instead of using accessor
    methods. And the book actually suggests using accessor methods.
    Why it is better to use constructors, accessor, and mutator methods on private instance variables?
    I am not very clear on this concept, why accessor or mutator methods are better ?
    I think the book implies emp.getEmployeeid() is the better approach, am I right ? but why ?
    Thanks in advance !
    Phil

    Thanks ! But, I can do something like this..
    class Department {
    Employee emp = new Employee();
    int id = emp.employeeid;
    It looks ok, isn't it ?Only if employeeid is a public variable. If it is marked private in the Employee class then it won't work.
    Another reason for using accessor and mutator methods is so that the author of the class can have control over how the private variables are used and to trap bad values.
    If the variables are left public then the data contained in them could be corrupted by another class manipulating them. Making the variable private and having a mutator method allows more control over what gets stored in the variable.

  • Publicizing controls vs  accessor methods

    hi. this might be a stupid question but i really want to knw why i should avoid declaring controls such as textboxes, buttons, etc.. as public instead of using accessor methods to modify its properties from a different class. i was wondering if anyone could give me the "real world" justification for it and not just give me a textbook answer. thanks.

    I asked that question because I found the following one on the example of mock:
    A class can not be called "tightly encapsulated" unless which of the following is true?
    a.      All member fields are declared final.
    b.      The class is not anonymous.
    c.      The internal data model can be read and modified only through accessor and mutator methods.
    d.      The class is an inner class.
    e.      None of the above
    I think it would be found in:
    Section 5: OO Concepts
    all right?

  • My constructor method is bogged!

    Hi There,
    I've got some problems with constructor methods in my program, of course the constructors look fine to me, but then faulty code usually looks good to any programmer after enough hours! Here is some of my code, firstly the following snippet shows the objects being instantiated.
    public static ButtonData BtData1;
    public static ButtonData BtData2;
    public static ButtonData BtData3;
    public static ButtonData BtData4;
    public static ButtonData BtData5;
    public static void main(String[] args)
        try{
          inStream = new FileInputStream("ObjStore");
          objStreamIn = new ObjectInputStream(inStream);
          if(objStreamIn.available() == 0)      
            objStreamIn.close();                
            inStream.close();                   
            BtData1 = new ButtonData("Link1",null);
            BtData2 = new ButtonData("Link2",null);
            BtData3 = new ButtonData("Link3",null);
            BtData4 = new ButtonData("Link4","Zero");
            BtData5 = new ButtonData("Link5","Zero");
          else
        }catch(IOException e){}
        GUI xyz = new GUI();            
    }Alot of the above code is related to serialization -- mainly checking to see whether or not objects already exist on file, and if they do not, instantiating them. Notice that the above constructors have different parameters or arguments (I can't remember which word describes it best!) -- it doesn't seem to matter whether I use two strings such as ("Link4","Zero") or ("Link1",null) -- both create errors. The class that is instantiated looks like this:
    import java.io.*;
    public class ButtonData implements Serializable
      String Name;             
      String Path;             
      ButtonData(String Name,String Path)
        this.Name = Name;
        this.Path = Path;
      protected String getName()
        return Name;
      protected String getPath()
        return Path;
      protected void setName()
        Name = Begin.LinkName.getText();
      protected void setPath()
        Path = Begin.ExecT.getText();
    }As far as I can tell the constructor above follows all the relevant syntax rules, as does the first snippet of code that I provided -- where the objects are instantiated. I will probably feel like a real meat head if I have done something dump and obvious, however I have double checked the code and it looks fine to me. When trying to compile the code I get the following error messages (using JBuilder7) -- these error messages highlight the relevant sections of the first code snippet I provided:
    "Begin.java": Error #: 300 : constructor ButtonData(java.lang.String, null) not found in class quicklauncher2.ButtonData at line 61, column 23
    "Begin.java": Error #: 300 : constructor ButtonData(java.lang.String, null) not found in class quicklauncher2.ButtonData at line 62, column 23
    "Begin.java": Error #: 300 : constructor ButtonData(java.lang.String, null) not found in class quicklauncher2.ButtonData at line 63, column 23
    "Begin.java": Error #: 300 : constructor ButtonData(java.lang.String, java.lang.String) not found in class quicklauncher2.ButtonData at line 64, column 23
    "Begin.java": Error #: 300 : constructor ButtonData(java.lang.String, java.lang.String) not found in class quicklauncher2.ButtonData at line 65, column 23If anybody can shed some light on what is going on here it will be greatly appreciated.
    Thanks

    Thanks everybody for your kind constributions, unfortunately I have tried all suggestion provided and have come up with naught. As both classes are in the same package, the question of scope is resolved, and making the ButtonData objects constructor public has no effect on the error messages displayed. I have also modified the ButtonData class so that accessor and mutator methods are public and variables are private, unfortunately this also has had no effect on the immediate error messages. If anybody has further suggestions they will be greatly appreciated. I thought perhaps that the issue with the constructor may be related to the implementation of the serializalbe interface ----->
    beyond that idea I am seriously stuck!

  • Help required: Using objects/methods in other classes

    Hi
    Say you have a class that has a private string instance variable and you have a accessor and mutator method for this object in that class.
    You have another class that needs to access this object via the accessor and mutator methods. How do you do this? When I try I only get nullPointerExceptions or Stack Overflows!!! If anyone can provide some code on how to do this successfully then that will be most appreciated. Thanks.

    Kayaman gave you the right answer
    public class MyDataClass {
    private String importantString;
    public void setImpString(String s) {
    importantString = s;
    public String getImpString() {
    return importantString;
    public class MyMainClass {
    public static void main(String[] args) {
    MyDataClass a = new MyDataClass();
    a.setImpString("This is important");
    System.out.println(a.getImpString());
    }Note that he sets the value of the imp string before trying to get it. The nullpointer that you say is probably because you dont do that.
    Also When you aks a question a little humility doesnt hurt.
    You do need a tutorial first.

  • What's the best way to use an enum to validate statuses

    I am trying to write and use an enum to represent a status code and validate status code values. Ultimately the input data from another system and the database will be 1 or 2 i.e.the indexes and the java code will use the LIVE and CANCELLED when referring to the status. The code I have written
    public class TestEntityStatus {
         private static EntityStatusImpl es;
         public static void main(final String args[]){
                    es =  new EntityStatusImpl();  
                    es.setStatusCode("1"); // valid test
                    es.setStatusCode("3"); // invalid test
    }The EntityStatusImpl class:
    public class EntityStatusImpl {
        private String statusCode;
        public EntityStatusImpl() {
        public final String getStatusCode() {
            return statusCode;
        public final void setStatusCode(final String statusCode) {
             String allStsIndexesAsRegExpr = "[";                                                                                 //
                EntityStatus allStatuses [] = EntityStatus.values();                                                     // would like to 
                for(EntityStatus e : allStatuses)                                                                                // put this code
                    allStsIndexesAsRegExpr = allStsIndexesAsRegExpr + e.getStatusCode();   // in the enum
                allStsIndexesAsRegExpr = allStsIndexesAsRegExpr + "]";                                        // EntityStatus
                System.out.println(" allStsIndexesAsRegExpr = " + allStsIndexesAsRegExpr);           //
                 if (statusCode.matches(allStsIndexesAsRegExpr)) {
                     this.statusCode = statusCode;          
                 else {
                      throw new IllegalArgumentException("Entity status " + statusCode + " is invalid");     
    }The EntityStatus enum has a method "getAllIndexesAsRegex" which I would like to call. However, my understanding of enums is preventing me from doing so.
    If I declared an EntityStatus, I expected that I would be able to get all of the indexes back as follows in
    EntityStatus x;
    x.getAllIndexesAsRegex();
    Instead I have to copied the code from the enum into the setStatusCode method above, where it works but does not seem to be in the right place.
    public enum EntityStatus {
                     LIVE(1), CANCELLED(2);
                     private int index;
                 private EntityStatus(int index) {
                     this.index = index;
                  public int getStatusCode(){
                           return index; 
                  public String getAllIndexesAsRegex(){
                       String output = "[";
                       PromiseStatus allStatuses [] = PromiseStatus.values();
                       for(PromiseStatus p : allStatuses)
                            output = output + p.getStatusCode();
                       output = output + "]";
                       return output;
         }The java tutorial doesn't seem to throw much light on this type of application of enums for me, neither does Herbert Schilt's excellent book on Java 5.
    Can anyone spot any flaws in my logic or suggest better ways of achieving this?

    If you want to ensure type safety and retrict the user to a range of values it seems to me you are over complicating
    the implementation. Simply change your Impl class accessor and mutator methods to accept and return the enum
    type respectively. For example:
    private EntityStatus entityStatus;
    public EntityStatus getEntityStatus()
       return entityStatus;
    public void setEntityStatus(EntityStatus entityStatus)
      if (entityStatus == null)
        throw new IllegalArgumentException("Invalid entity status!");
      this.entityStatus = entityStatus;
    }The one downside is that you are retrieving the actual underlying enum values from external source systems which you need to map back to your
    enum types. Unfortunately the Enum class does not have a method that will return what you need (the valueOf method returns the enum type
    based on the enum name). However you can provide a method in your enum class that will map the external source values to the enum. Below is
    one such implemetation.
    import java.util.HashMap;
    import java.util.Map;
    public enum EntityStatus
      LIVE("1"),
      CANCELLED("2");
      private String statusCode;
      private static Map<String,EntityStatus> enumMap = new HashMap<String,EntityStatus>(EntityStatus.values().length);
      static
        enumMap.put(LIVE.getStatusCode(),LIVE);
        enumMap.put(CANCELLED.getStatusCode(),CANCELLED);
      private EntityStatus(String statusCode)
        this.statusCode = statusCode;
      public String getStatusCode()
        return statusCode;
      public static synchronized EntityStatus deriveObject(String statusCode)
        return enumMap.get(statusCode);
    }Below is a usage example:
      public static void main(String args[])
        EntityStatus status1 = EntityStatus.deriveObject("1");
        EntityStatus status2 = EntityStatus.deriveObject("2");
        EntityStatus status3 = EntityStatus.deriveObject("3");
        System.out.println(status1);
        System.out.println(status2);
        System.out.println(status3);
      }

  • Component binding inside h:dataTable fails

    Hi,
    I'd like to create a component binding for each commandLink to a distinct child bean inside an h:dataTable like so:
    <h:dataTable value="#{parent.children}" var="child">
        <h:column>
            <h:commandLink binding="#{child.command1}" value="do it to it for #{child}" action="#{child.action}"/>
        </h:column>
    </h:dataTable>But whenever I try to render this page I get an exception stating that "child is null" and binding cannot be performed. If I remove 'binding="#{child.command1}"', however, everything works fine. I guess this is happening because 'var="child"' in h:dataTable gets evaluated after bindings are created. How can I get around that - I really need to be able to refer distinctly refer to UIComponents in each row.
    Confused...
    thanks
    -nikita

    I created a seperate class to handle the requests ActivationRequestBuilder and put the code in there .
    if you want to refer to each row in the backing bean .
    create a variable of type HtmlDataTable .
    private HtmlDataTable tenantDataTable;
    set up accessor and mutator methods for this variable.
    In your jsp in the DataTable
    <h:dataTable binding="#{activationRequestBuilder.tenantDataTable}"
    <h:commandLink title="Delete Tenant section"
    immediate="true" action="#{activationRequestBuilder.deleteTenantLocationSection}">
    public String deleteTenantLocationSection(){
    (TenantLocationRecordBean) this.getTenantDataTable().getRowData();
    This is just snippets of code but you should get the idea of what I have done here .I had multiple sections in a page so each row was a TenantLocationRecordBean .

  • How to use Set as field of my object?

    public class FileSystem implements Serializable{
        private Node current;
        private final Node root;
        private Node iterator;
        private Node source;
        private Node tempNode;
        private Set<String> commandSet;
        /** Creates a new instance of FileSystem */
      public FileSystem() {
            FileSystemObject fso=new FileSystemObject("/",true);
            NodeItem ni=new NodeItem(fso,"d"+fso.getName());
            Node node=new Node();
            node.setNodeItem(ni);
            root = current = node;
            commandSet=Collections.;
            commandSet.add("pwd");
            commandSet.add("cd");
            commandSet.add("ls");
            commandSet.add("mkfile");
            commandSet.add("mkdir");
            commandSet.add("cp");
            commandSet.add("cpdir");
            commandSet.add("mv");
            commandSet.add("mvdir");
            commandSet.add("rm");
            commandSet.add("rmdir");
            pwd();
        }  As you can see from the above code i have a Set field named commandSet for my FileSystem Object .. in order to be able to write a code like :
    if(commandSet.contains(String str)) somewhere in my program how must i initialize this Set... the commandSet is i&#351;ntended to be a set of Strings..

    duffymo wrote:
    I thought the two were pretty similar. What's "so much easier"?
    %There are similarities syntactically they have a great deal in common. C# does things to try to be helpful that I find onerous and distasteful. As an example we (as java developers) take accessor and mutator methods for granted. If I want to get the value of the the framitz member data I'm going to call getFramitz(). This is a given that we accept as cannon. C# however wraps the call to the accessors and mutators and takes care of that little detail so the code
    Widget w = new Widget() ;
    w.framitz ;might be calling an accessor method under the hood (without telling you) or it could be accessing a public member directly without calling an accessor. This sort of help I neither want nor need.
    This is the sort of thing about .Net in general that drives me insane and makes me not want to use it.
    PS.

  • How to use PropertyChangeSupport for a bean from another bean

    Hi all,
    I have a bean A that doesnot implements the PropertyChangeListener or have a PropertyChangeSupport as one of its member and I cant change its design. I want to fire an PropertyChangeEvent when a property is changed. I added A to PropertyChangeSupport of another bean B. The problem is that even if the Property of Bean A is changed it doesnot fire a event. Can anybody let me know how to do it?
    Thanks,
    Amit

    You need to wrap bean A inside another bean (B) that
    implements the accessor and mutator methods of Bean A
    and adds property change support in those methods
    where appropriate. You hide the actual instance of
    bean A inside an instance of bean B so no instances of
    bean A are visible to the application.This is OK, unless you don't want to change all places where A is referenced. You could subclass B from A, as long as the accessor and mutator methods are not final. Of course, instantation still has to know about B and you will have to cast to B, or use reflection, to add and remove the listeners.

  • Need help tp check my code

    Hi, I have been having too busy with my other project and now running issue with java that I can't seem to get the Search() working even though I could compile and enter data...hopefully your advice will be helpful. Thanks!
    Create a user-defined class called Employee with the following characteristics.
    Data members whose accessibility should be restricted to members of the immediate class and sub-classes only.
    1.     First name
    2. Last name
    3.     ID
    4.     Salary
    5.     Grade - single character P, F or C
    The following methods should be included in the Employee class
    1.     An appropriate constructor that will accept the Employee�s name, Salary and grade as parameters and initialize the data members accordingly. The ID may also be passed as a parameter OR it may be generated automatically. The ID field will be used as the �primary key� and as such no duplication should be allowed.
    2.     Accessor and mutator methods that provide accessibility to the data members.
    3.     A method that allows the salary of the employee to be increased.
    4.     A method that allows the grade of the Employee to be changed.
    5.     Override the toString method so details of the Employee may be returned as a String.
    EmployeeData.java
    import java.io.*;
    // Employee class declaration.
    class Employees
         protected String first_name;
         protected String last_name;
         protected int id;
         protected double salary;
         protected char grade;
         public Employees(int a_id)
         int id = a_id;
         public Employees()
         // constructor
          public Employees(String first_name, String last_name, int id, double salary, char grade)
         this.first_name = first_name;
         this.last_name = last_name;
         this.salary = salary;
         this.grade = grade;
         this.id = id;
         //Accessor and mutator methods that provide accessibility to the data members.
         public int getid()
              return this.id;
         //accessor
         public double getsalary()
              return this.salary;
         public char getGrade()
              return this.grade;
         //mutator
         public void setSalary(double salary)
              this.salary = salary;
         public void setGrade(char grade)
              this.grade = grade;
         //A method that allows the salary of the employee to be increased.
         public void increaseSalary(double newSalary)
              this.salary = salary + newSalary;
         //A method that allows the grade of the Employee to be changed
         public void changeGrade(char grade)
              this.grade = grade;
         public void display()
              System.out.println("First Name " + first_name);
              System.out.println("Last Name  " + last_name);
              System.out.println("Salary  " + salary);
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////Employee.java
    import java.io.*;
    class EmployeeData extends Employees
         //Override the toString method so details of the Employee may be returned as a String.
         public String toString () {
              String info = super.toString();
              return info = "Name: " + first_name + " " + last_name + "\nID: " + id + "\nSalary: " + salary + "\nGrade: " + grade;
         //The ID field will be used as the �primary key� and as such no duplication should be allowed.
         private Employees database[];
         public int numOfEmployee;
         static BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
         public EmployeeData()
              //numOfEmployee = 0;
              database = new Employees[10];
         public void DisplayEmployee() throws Exception
                   int index = search(id);
                   if (index!= -1)
                        database[index].display();
         public void RegEvaluation() throws Exception
                   System.out.println("Enter Employee Data");
                   System.out.print("Enter First name : ");
                   String a_first_name = input.readLine();
                   System.out.print("Enter Last name : ");
                   String a_last_name = input.readLine();
                   System.out.print("Enter Employee ID: ");
                   int a_id = Integer.parseInt(input.readLine());
                   System.out.print("Enter Employee Salary: ");
                   double a_salary = Double.parseDouble(input.readLine());
                   System.out.print("Enter Employee Grade: ");
                   char a_grade = (char)input.read();
                   int index = search(id);
                   if (index != -1)
                        System.out.println("numOfEmployee " + numOfEmployee);
                        System.out.println("-------------------------------------");
                        database[numOfEmployee] = new Employees(a_first_name, a_last_name, a_id, a_salary, a_grade);
                        System.out.println("Employee Account Created!");
                        System.out.println("-------------------------------------");
                        numOfEmployee++;
         // To check for duplicate ID values
         public int search(int findID) throws Exception
              for(int x = 0; x < numOfEmployee; x++)
                   if(database[x].getid() == findID)
                        System.out.println("\nEmployee ID exists");
              }return 0;
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////useEmployeeData.java
    class useEmployeeData
         public static void main(String args[]) throws Exception
              EmployeeData EmployeeData = new EmployeeData();
              EmployeeData.RegEvaluation();
              EmployeeData.DisplayEmployee();
              EmployeeData EmployeeData2 = new EmployeeData();
              EmployeeData2.RegEvaluation();
              EmployeeData2.DisplayEmployee();
    }Message was edited by:
    proyb

    when I execute the program, it will ask for employee:
    first name:
    last name:
    ID:
    salary:
    grade:
    and on the second run, I was surprise why the first name and last name are on the same line...
    first name: last name:
    and continue to key in data as require.
    Suppose I try to key in same ID number, it did not show an error message and create another object, now there are 2 object with similar keys.
    Message was edited by:
    proyb

  • Plz help!! array of object (for search)

    i've got few questions of array of object
    1-how to search for a price that is greater than 300 in the array of object
    and how to list all of them?
    2- how to search for the smallest price in the array of object, and how to list?
    can anyone provde a java code for me:P?
    but plz don't too complex
    coz i'm a learner of javaT_T

    _< i still can't understand, and dunno how to change into the code that i needand you guyz help me change it?
    /*wirte the driver program which will define and create an array of
    objects instantiated from the class WaterBill
    Create Accessor and Mutator methods to get/set data from the class.
    write code within the driver method to perfrom the following:
    a) The final total of funds
    b) To search for accounts greater than $300 in the array of objects,
         and list all the customer details
    c)To search for the lowest bill in the array of objects, and list
    those customer dtails
    Class definitions and Objects  using price
    import java.text.*;
    import javax.swing.JOptionPane;
    public class Pre_pb3
         public static void main(String []args)
              int  TTc=0;
              int accNum[]=new int[20];
              String name[]=new String[20], output, stans, display; //stAccNum, stUsage, stTTc;
              double usage[]=new double[20];
              double TTa=0.0;
              double price[]=new double[20];
              char ans;
              double acctG,lowest;
              int i=0;
              waterBill MYwaterBill = new waterBill();
              ans='Y';
              while (!(ans=='N'))
                   name=inputName();
                   accNum[i]=inputAccNum();
                   usage[i]=inputUsage();
                   price[i]=calculateAmountOwing(usage[i]);
                   TTa=MYwaterBill.TTaPrice(price[i]);
                   output=MYwaterBill.outputInfo(name[i], accNum[i], usage[i], price[i]);
                   waterBill MYwaterBill2= new waterBill(name[i], accNum[i],usage[i], price[i]);     
                   stans=JOptionPane.showInputDialog("Do you wanna continue?, (Y)es, (N)o");
                   stans = stans.substring(0, 1);
                   stans=stans.toUpperCase();
                   ans=stans.charAt(0);
                   TTc++;     
              MYwaterBill.outputoutput(TTc, TTa);
              MYwaterBill.findGreat();     //b)
              MYwaterBill.searchDetail();     //c)
              System.exit(0);                                                  
         public static String inputName()
                   String name;
                   name=JOptionPane.showInputDialog("Enter Name ");
                   return name;
         public static int inputAccNum()
              int accNum;
              String stAccNum;
              stAccNum=JOptionPane.showInputDialog("Enter Account Number");
              accNum=Integer.parseInt(stAccNum);
              return accNum;
         public static double inputUsage()
              double usage;
              String stUsage;
              stUsage=JOptionPane.showInputDialog("Enter Water Usage");
              usage=Double.parseDouble(stUsage);
              if (!(usage>=0 && usage<=99999999))
                   System.out.println("water useage is invalid");
                   System.exit(0);
              return usage;
         public static double calculateAmountOwing(double usage)
              double price=0.0;
              if (usage>=0)
                   if (usage<=10000)
                        price=(10000/10)*0.01;
                   else if (usage>10000)
                        price=((10000/10)*0.01)+(((usage-10000)/10)*0.02);
              else
                        System.out.println("Error of usage");
                   return price;
    class waterBill
         private static     int TTc=0 ,accNum=0;
         private static String name, stAccNum, stUsage, stTTc;
         private static String output=" ";
         private static double usage=0.0;
         private static double TTa=0.0;
         private static double price=0.0;
         private static String lowest;
         public waterBill()
              name=" ";
              accNum=0;
              usage=0.0;
              price=0.0;
         public waterBill(String n,int an, double us, double p)
              setName(n);
              setAccNum(an);
              setUsage(us);
              setPrice(p);
         public void setName(String n)
              name=n;
         public void setAccNum(int an)
              accNum=an;
         public void setUsage(double us)
              usage=us;
         public void setPrice(double p)
              price=p;
         public String getName()
              return name;
         public int getAccNum()
              return accNum;
         public double getUsage()
              return usage;
         public double getPrice()
              return price;
         public double TTaPrice(double price)
              TTa=TTa + price;
              return TTa;
         public String outputInfo(String name, int accNum, double usage, double price )
              String output=" ";                         
              output: System.out.println( "Account Number: "+ accNum +
                                       "\nWater Usage: " + usage +
                                       "\nCost Owing: " price
                                       "\nName: "+ name+"\n");
              return output;
         public void outputoutput(int TTc, double TTa)
              display:     System.out.println("Total customer: "+ TTc +
                                  "\nTotal amount owing: " + TTa + "\n\n");
         public void findGreat()//search the a/c that is greater than 300.
              //dunno how to do, so i just leave it blank^^"
              public String searchDetail()//search the smallest a/c
              //same...dunno how to doT_T     

  • I need a quick help plz :(

    Ok i have a question and i tried to answer it but i still have a few errors..can someone please give me my code back with the correction plz ? :(.... and i need it in less then a day...i know am being pushy am so sorry but i really need it
    the Q is
    Consider a superclass PurchaseItem which models customer�s purchases. This class has:
    -     two private instance variables name (String) and unitPrice (double).
    -     One constructor to initialize the instance variables.
    -     A default constructor to initialize name to �no item�, and unitPrice to 0. use this()
    -     A method getPrice that returns the unitPrice.
    -     Accessor and mutator methods.
    -     A toString method to return the name of the item followed by @ symbol, then the unitPrice.
    Consider two subclasses WeighedItem and CountedItem. WeighedItem has an additional instance variable weight (double) in Kg while CountedItem has an additional variable quantity (int) both private.
    - Write an appropriate constructor for each of the classes making use of the constructor of the superclass in defining those of the subclasses.
    - Override getPrice method that returns the price of the purchasedItem based on its unit price and weight (WeighedItem), or quantity (CountedItem). Make use of getPrice of the superclass
    - Override also toString method for each class making use of the toString method of the superclass in defining those of the subclasses.
    toString should return something that can be printed on the receipt.
    For example
    Banana @ 3.00 1.37Kg 4.11 SR (in case of WeighedItem class)
    Pens @ 4.5 10 units 45 SR (in case of CountedItem class)
    Write an application class where you construct objects from the two subclasses and print them on the screen.
    and i wrote this program
    public class PurchaseItem {
         private String name ;
         private double unitprice;
         public PurchaseItem (String name , double unitprice) {
              this.name = name;
              this.uniteprice = unitprice;
         public PurchaseItem() {
              name = "no item" :
              uniteprice = o;
    public double getunitprice() {
         return uniteprice;
    public String getname() {
         return name;
    public void setName(String newName){
              this.name = newName;
    public void setuniteprice(double newuniteprice){
              this.uniteprice = newuniteprice;
    public String toString(){
         return "\nitem name:" + name + "@" + "\nuniteprice:" + uniteprice;
    public class WeighedItem extends PurchaseItem {
         private double kg;
         public WeighedItem(String name , double unitprice , double kg) {
         super (name , uniteprice);
         this.kg = kg;
         public double getunitprice() {
              return uniteprice + "" + kg;
    public String toString() {
         return "\nitem name:" + name + "@" +"\item weight:" + kg + "\nuniteprice:" + uniteprice;
    public class counteditem extends PurchaseItem {
         private int quantity;
         public counteditem(String name , double unitprice , int quantity) {
         super (name , uniteprice);
         this.quantity = quantity;
         public double getunitprice() {
              return uniteprice + "" + quantity;
    public String toString() {
         return "\nitem name:" + name + "@" +"\quantity:" + quantity + "\nuniteprice:" + uniteprice;
    i know i still miss the test class but that not important now i just wish someone will help me with the corrections of the above code PLZ
    thanx in advance :(

    When you post code, wrap it in [code] tags so we can read it.
    Also indent it sanely.
    If you can't compile, post the compiler error messages.
    If it runs but throws an exception, post the stack trace.
    If if runs without throwing an exception but you've foolishly written your code to silently catch exceptions, fix your code by actually printing the stack trace in the catch blocks, then rerun.
    If your code smartly reports exceptions, and it runs, but it still doesn't work, try adding some debugging code (displaying the values of various variables and showing when methods begin and end, for example) to help narrow down the problem. When you've narrowed down the problem, try writing a small, compilable program that exhibits the same problem. If you can't fix it with that, post the example program here.

  • Maximizing communication between objects.

    Hi,
    I have a question concerning communication between objects. Particularly I want to learn to maximize communication between objects. Obviously there are several ways of increasing communication between objects, unfortunately I only really understand one methodology, which is as follows:
    For example:
    If I were to create an object called GUI of class UserInterFace, like so
    class UserInterface extends JFrame
      private variable1;
      private variable2;
      UserInterface()
        setBounds(x,y,width,height);
        setVisible(true);
    }I could then create an object called fileOps of class FileOperations and pass the entire GUI object into the constructor of the fileOps class, as follows:
    class FileOperations
      private FileReader input;
      private FileWriter output;
      private UserInterface GUI;
      FileOperations(UserInterface GUI)  //GUI object introduced.
        this.GUI = GUI;
    }By following the code fragments above it becomes obvious that I can establish communications between the fileOps object and the GUI object. With code similar to the above; fileOps will be able to access all of the accessor and mutator methods within object GUI. Using the above methodology always requires making all variables private and accompanying those variables with public methods (thus preserving encapsulation).
    If anybody can suggest any other methodologies for increasing communication between objects they will be greatly appreicated. Of interest to me is how one can go about ensuring complete two way communication between objects, my example above is rather one sided (fileOps can see GUI, but not vice versa). Obviously the instantiation of objects must occur in some procedural sequence, I want to know how to capitilize on this. Suggestions to read a particular book will be appreciated, however suggestions born from peoples experiences are most desired. Thanks.
    Regards
    David

    Rommie and Rajesh,
    Thank you both kindly for sharing your time and valuable knowledge. As I have only been programming with Java for a year part time (as one section of a Computer Systems Diploma) I consider myself to be a beginner in programming terms. I want to do really well with Java as quickly as possible and you have both helped me tremendously.
    Rommie the methodology that you have passed onto me is great, thankyou so much, I feel like a new section of Java has completely opened to me. I will be using the third "reference" class methodology from everyday now on.
    Rajesh your words are encouraging, and I will be reading up on Hierarchy and Aggregation immediately. When you said "Before using either, decide on the existence of the object, its intended functionalities e.t.c. ...", could you please explain with an example as to where Hierarchy is desirable and where Aggregation is desirable.
    Please feel free to e-mail me with further suggestions if you come up with something else that aids in the communication between objects.
    E-mail: [email protected]
    Thanks again.
    Regards
    David

Maybe you are looking for

  • How bad can a company be?

    I called BT around mid May. I informed them i was going to move to a new flat in NW2 in June. I told them the flat is being completely renovated and that i wanted to get a phone line. The BT employee on the phone did some checks and confirmed to me t

  • My IPad Air is frozen with a white screen and Apple Logo on it.

    My Ipad Air is frozen with the white screen and apple logo.  I've tried resetting it several times and that doesn't help.  I tried connecting to ITunes, but it isn't recognizing the device.  The battery is fully charged, at least for now, so I am not

  • Problem of showing image in opera

    hi, I have used following code for for showing image with jsp: <img src="<%=image%>"> height="100" width="100">When i open this with Internet Explorer then it can show image. But whwn open it in Opera then it cannot show images. What's the problem of

  • Schema upgrade

    Hello guys say that I took an export of a schema from database 10G and import it into a 11G database and now I would like to upgrade that schema, Can some one point me to the oracle docs that explains this process. When i google "oracle schema upgrad

  • MAC PRO TAKEN APART!

    Mac Pro taken apart! By Powermax 08/08/2006 10:40 PST http://www.powermax.com/articles_reviews/article.php?id=32