Creating Instance Variables And Constructors For Map Class
Mar 27, 2014
I have to create an application that deals with maps.
I first have to create the instance variables for the class.
So very simply if my hashmap is going to consist of football clubs and players. Football clubs being a string value for the key and players being a set of strings for the values. How would I go about creating the instance variable in a class for this?
I can't seem to find anything that specifically deals with instance variables and constructors for maps.
I am having some problem accessing variables from an array instance of a class. Heres what i have done;
In the main class:
Example obj[]= new Example[4];
In the main class constructor:
obj[0] = new Example(0); obj[1] = new Example(1); obj[2] = new Example(2); obj[3] = new Example(3);
In the main update() method:
if(condition) //update
In the Example class constructor:
private boolean change = false;
In the Example class update() method:
if(x >20) change= true;
Now, i want to access the variable change from the main class, how do i do it? The 'condition' in the if statement is the condition of wether the change variable ia true or false. How do i access it?
Create a class called Employee that includes three pieces of information as instance variables:
-Employee ID (string type) -first name (string type) (default value 'John') -last name (string type) (default value 'Smith') and -monthly salary (type double). -No argument constructor that initializes the three instance variables. The employee id should be generated using the following process:
The employee id should be a combination of first initial, last initial and a number starting from 10001 for the first employee and increasing by one for each employee. e.g. if John Smith is the first employee then its id will be JS10001 and if George Brown is the second employee then its id will be GB10002
-Provide get and set methods for each instance variable. The set method for monthly salary should ensure that its value remains positive - if an attempt is made to assign a negative value, leave the original value.
package Threads; // THIS PROGRAM WILL HAVE TWO THREADS i.e. "main" AND ANOTHER THREAD (SYSTEM WILL NAME IT "Thread-0" //THE STORY IS THAT WE WILL START Thread-0 FROM main AND LET IT EXECUTE. //main WILL WAIT AND LET IT EXECUTE FOR 5 MINUTES. //IF IT FINISHES ITS EXECUTION BEFORE 5 MINUTES, WELL AND GOOD; //BUT IF IT DOESN'T, WE WILL INTERRUPT IT. //AFTER INTERRUPTION, WE WILL DECIDE TO WAIT INDEFINITELY.
public class SimpleThreadsCopy { public static void threadMessage(String s){ String sThreadName= Thread.currentThread().getName(); System.out.format("%s: %s%n", sThreadName, s);
[Code] ....
The statement against which I have written many *'s gives the following error.
No enclosing instance of type SimpleThreadsCopy is accessible. Must qualify the allocation with an enclosing instance of type SimpleThreadsCopy (e.g. x.new A() where x is an instance of SimpleThreadsCopy).
Now that a similar "error-free" code is given here, what's wrong with this piece of code and what should I do about it?
Trying to understand the error statement, I replaced the erroneous statement with
Java Code : Thread t= new Thread(new SimpleThreadsCopy().new MessageLoop()); mh_sh_highlight_all('java');
And the error got fixed. From that I understand that the inner class is just kinda a nonstatic member of the outer class and it will be accessed by the objects of the outer class only.
But then why doesn't the code in the tutorial give an error?
As web server has multiple threads to serve client requests in Thread Pool & to ensure Thread Safety we should not use any variables or Objects at Instance/Class level.But in case of Session Variable which one is the Best Practice as the Session object is used by all the requests to have the same Session ID.
My Code :
public class MyServlet extends HttpServlet { private static Logger log = Logger.getLogger(ClientRegistrationServlet.class); private HttpSession session; /* This is used at Instance Level*/ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
public String firstName() Returns the customer's first name public String lastName() Returns the customer's last name public double balance() Returns the customer's account balance
Finally I need to create a driver to test my class. And create several accounts and verify that the first name, last name, and balance methods work properly. This is my code below.. I don't know if I did it right.
public class BankAccount { String firstName, lastName; double balance; public BankAccount(String firstName, String lastName, double balance) {
I have a class called Sprite which extends its several subclasses. Therefore, there are a lot of different Sprite classes, the thing is however, most of those subclasses have unique types of variables which I want to only be included in those particular subclasses, not anywhere else. For instance, I might have a variable measuring distance in one subclass, and in another subclass there might be a height variable inherent. I don't want the first subclass to have both variables, neither the second or the main class. Because before I initialize my subclasses, I need to create the constructors of those subclasses in the main Sprite class first because it doesn't have the unique variables which those classes consist of. How do I prevent that? Now I have to create the unique constructors and variables for every subclass, when I only want them in their associated classes.
So far in my assignment I have successfully opened a text file. However I am required to do more:
1) As each line of text (containing names and ages) is read a new Runner object is created with its instance variables set thus: ! (Runner class already created )!
- name : set directly set from the value in the file - agaGroup : can be worked out from the given ages: < 18 should be 'junior' > 55 should be 'senior' the rest should be 'standard'
2) the instance of Runner should be added to the list referenced by the instance variable runners.
I have used if statements to create the junior list, however I do not see the full list of names and ages in the variable runners as I am requested to.
I am sure there is a for loop involved somewhere but I do not know how to:
a) use the for loop in my method add a new Runner object with the variable mentioned.
I include the code I have done so far as a file - p.s I use Bluej.
public class MarathonAdmin { // instance variables private String runners; private String age;
Do inherited methods use their instance variables or do they use the ones in the method that inherits them?
For example, Class B extends Class A. Class A and B both have the instance variable "potato". A client program tries to use method "cut" using an object of Class B, but class B has no cut method. So, class B uses the "cut" method inherited from class A. What I want to know is will that cut class A's potato or class B's?
so, i was reading my java book and learning about objects and methods and it starts talking about Encapsulation and mentions that it's good practice to set instance variables as private and instead of accessing the instance variables directly, we should create a set method and get method to get and set the stuff we want to pass to the class containing the object...
for example, in this class, we're passing the integer 70 for object dog one and integer 8 for object dog two for the dog class... and these these 2 integers are sent to the setsize method so we're not accessing instance variable size directly.
i dont quite get it though....if we the programmer are the one deciding what size the integer is for the dog, and the setsize method takes the one.setSize(70) or (8) and puts them in setsize(int s) as s... but only to copy that integer stored in s back to private int size.... why do we even need to bother with making these two extra methods such as setSize, getSize?
in the book it says that... well what if the code gets into the wrong hand and someone writes something like one.setSize(0) then you would get a dog with size 0 which is essentially illogical. but then again, i'm the programmer, and i am the person who writes the code and passing the right integer.The reason for public and private... that part i understand... i can see why if a variable's data can get changed amidst the code during calculations and you dont want it to directly change the original variable and have it mess up the code, but this code from the book just a bad example of demonstrating the reason? since we manually pass the information ourselves and passing it to method setSize... and all setSize does is stores it in another integer, only to copy it right away to size (which is the original private variable we were tryign to protect?
Any simple code to demonstrate how the code might end up changing an instance variable and why we would want to protect it by using private?
class GoodDog { private int size; public int getSize() { return size; } public void setSize(int s) { size = s;
why overridden doesn't apply to variables. However, instance variables are stored inside the object.I ran below program and expected to print "two" but it gets printed "one".
class SupCont { String s = "one"; } class Cont extends SupCont { public static void main(String a[]) { String s = "two"; SupCont c = new Cont(); System.out.println(c.s); } }
I am suppose to create a rectangle and I have created two classes; Rectangle.java and RectangleTester.Java.
So far my code for the class Rentangle.java is:
package edu.sbcc.hw2; public class Rectangle { private int width = 25; private int height = 25; public rectangle(int xcoord, int ycoord, int thewidth, int theheight) { this.width = width; this.height = height; } public int getWidth() { return width;
So for my assignment I need two instance variables for height and width for which I have, but it says in the assignment I need methods (settings and getters /mutators and accessors that allow manipulation of my instance variables which is a little confusing. Do I put these methods on Rectangle.java or RectangleTester.java.
The same goes for the calculateArea, where am I suppose to put this?
I thought static methods could never use instance variables, because they wouldn't know which instance to look at.
From Head First Java, p. 284: "A static method is not associated with a particular instance - only the class - so it cannot access any instance variable values of its class. It wouldn't know which instance's values to use."
Now I was answering some mock exam questions from Cameron McKenzie's SCJA book, and I don't understand one of the options. On page 205, the last question has an option that says: "Instance variables ... are not visible in static methods, unless passed in as arguments." This option is supposed to be correct. Now... how does that work?
I remember reading that a super() call to parent no-argument constructor is automatically inserted by compiler. So, if i have a chained hierarchy of classes (starting at top, with Object), will there be a chain of super() calls, going from bottom to top in the chain ? Will a super() call be inserted in child, if i provide a no-argument constructor for this class ?
I have two classes LightController & Circle. I need to use the LightController class to do the following:
Creates an instance of Circle with a diameter of 50 and a colour of OUColour.GREEN and assigns this new circle to the instance variable light.
Sets the xPos of light to 122. Sets the yPos of light to 162.
I am struggling to write the correct line of code to set the colour to green and set diameter to 50.
Code for the two classes below.
import ou.*; import java.util.*; /** * Class LightController * This class uses the Circle class, and the Shapes window to simulate a disco light, that grows and shrinks and changes colour. */
public class LightController { /* instance variables */ private Circle light; // simulates a circular disco light in the Shapes window private Random randomNumberGenerator;
class Test3 { } class MySub extends Test3 { } class Test4{ public static void main(String args[]) { MySub m = new MySub(); } }
I learned that if a class and its parent class both have no constructors, the compiler is supposed to complain. When I compiled Test4, i got no errors. why did it give no errors?
MyStack class have by default some fixed size of maximum elements, allow user of your class to specify in constructor what this maximum size is. Also add possibility to specify name of the stack in constructor. User can either create object without parameters, can specify only size or name, or both of them. And also override function toString(), that this code will print:
Write a class Month that represents one of the twelve months of the year. It should have three attributes for
the name of the month,
the number of days in the month, and
the birthstone.
Also add constructors and getter/setter methods to access the attributes.
You may use the following code to test your class.
Java Code:
import java.util.*; public class Month { // ADD CODE HERE!!! public static void main(String[] args) { Month[] months = new Month[12];
[Code] ....
So what I have added so far is (under public class month { :)
Java Code:
String monthName, monthBirthStone; int monthDays; public Month (String name, int days, String birthstone) { monthName = name; monthBirthStone=birthstone; monthDays=days; } mh_sh_highlight_all('java');
So I believe that is the constructor. I still do not understand several things:
What would I need the getter and setter for?
I tested it using just the above code, and using month 1 I got:
Month@5a1cfb56
This makes sense as I obviously didn't do anything in order to get it in a String format for the array. But I do not understand this still - how would I get the constructor to output a string (to then be in the array?)