Can Classes Be Immutable In Some Situations But Not Others
Feb 12, 2014
I have some complex objects I want to design. Most of the time I would like these objects to be immutable so that other classes cannot change their values. However, I also want to create an editor to create these objects and the editor will need to change the object's values. It would also be useful to be able to set the objects' fields one at a time during serialization rather than doing everything in a huge constructor.
C provides a way to make objects unchangeable by using the 'const' keyword, but Java doesn't have that. I could also wrap my objects in other accessor objects, but then I'm duplicating a lot of code. Are there any good ways to make my objects mutable only to certain other classes?
I would like to understand why only String class is immutable.
1. Why String class is immutable? What is the main reason for making String class as immutable. 2. Why there is no int pool or float pool or Integer pool etc, why only String pool.
The following codes shows an implementation of an enqueue function of a FIFO immutable queue, and the output result shows the String "c".
I don't understand why since I expected it should be null.
The head and the tail of an ImmutableQueue Object are two separate queue, and each time I call the enqueue function, it just return a new object with a new tail, however, the head is not modified except the first two times I call the function.
Therefore, I expected head.next.next should be a null element, but the result is not like that.
public class ImmutableQueue<E> { private int size =0; public Queue<E> head; public Queue<E> tail; public ImmutableQueue(){} private ImmutableQueue(Queue<E> hd, Queue<E> tl){ head=hd; tail=tl;
I have make the immutable class as below, Now my question is how I can test if my this class/object is immutable
package com.learning; import java.util.*; import java.util.Map.Entry; public final class ImmutableTest { private final int id; private final String name; private final HashMap<String, String> hm ;
[Code]...
How I can Test If it is immutable class without looking ?
The following codes shows an implementation of an enqueue function of a FIFO immutable queue, and the output result shows the String "c". I don't understand why since I expected it should be null.
The head and the tail of an ImmutableQueue Object are two separate queue, and each time I call the enqueue function, it just return a new object with a new tail, however, the head is not modified except the first two times I call the function.
Therefore, I expected head.next.next should be a null element, but the result is not like that.
public class ImmutableQueue<E> { public Queue<E> head; public Queue<E> tail; public ImmutableQueue(){} private ImmutableQueue(Queue<E> hd, Queue<E> tl){ head=hd; tail=tl;
String object is stored in a private final char array in String.java. private final char value[];
The basic characteristic of a final variable is that it can initialize a value only once. By marking the variable value as final, the class String makes sure that it can’t be reassigned a value.
so the String objects can be initialized only once but the above code shows that str1 was initialized first with "Java", then it can be re-assigned value "one" bcos the output is one. If it can be re-initialized, basic characteristic of final variable is not satisified and hence how can we call String objects are immutable?
I want to clarify it whether this below code, when running this loop, will it create separate string objects as strings are immutable or else, will it keep the same reference(as each time inside loop, we use the same name 'rslt') and assign new string value for this?
I'm doing an aggregation exercise that's suppose to find the volume and surface area of a cylinder. What I'm trying to do is pass values from one class, to a second class, and that second class passes values to a third class.
This may be a clearer explanation: The first class is the main program which sends values to the second and third class. The second class is used do calculations for a circle (a pre-existing class from another assignment). The third class grabs the values that the second class calculated and calculates those values with the one that was passed from the first class to the third class. The first class then prints the outcome.
Problem is when the program gets to the third class, it just calculates the value from the first class with the default constructor from the second class. It's like the second class never received the values from the first class. I think I'm missing a step, but I don't what it is.
First Class:
package circle; import java.util.Scanner; public class CylinderInput { static Scanner in = new Scanner(System.in); public static void main(String[] args) { //user defined variable
I'm quite new to Java. I have some trouble with understanding how to get two classes to get objects from each other (if that is the correct term).
Lets say I have a login class, in which I have a method checking what the user has entered into the console (I have not displayed the whole code, but this class works as it should and give the user an option to enter username and password and return it true if entered correct).
public static boolean validateUserPass(String userName, String password) { String[] user = {"admin"}; String[] passwords = {"firkanten"}; boolean check = false; for (int i = 0; i < user.length; i++) { if (userName.equals(user[i])) { if (password.equals(passwords[i])) { check = true;
Now, in another class I want a display box to appear on the screen and give the user three options: Click yes, no or cancel. I get this to run perfectly alone, this is not the hard part for me. I want the display box only to appear when the correct username and password is given, but I can't seem to figure out how to do this probably.
Regarding the code examples in Head First Java, this is from Chapter 5, regarding the beginning creation of the dot com game. There are two classes in quesiton
the first is the SimpleDotComTester class: public class SimpleDotComTester { public static void main(String[] args) { SimpleDotCom dot = new SimpleDotCom(); int[] locations = {2, 3, 4}; dot.setLocationCells(locations); String userGuess = "2"; String result = dot.checkYourself(userGuess); } }
and the second one is the code for the checkYourself () method in the SimpleDotCom class
public class SimpleDotCom { int[] locationCells; int numOfHits = 0;
public void setLocationCells(int[] locs)
[code]....
Now I noticed that both classes use a variable called result; the program runs fine, but assume from the example that you can use the same variable name two different classes;
design a class to conduct a survey of three hospitals. you want to know how many sectors (eg operation, children, gastronomic) each hospitals have, and how many doctors there are in each sector.
I have a Date class and Time class. Is it possible to pass Time object inside Date constructor so that toString function gives output as 12/05/2013 06:31:30 ?
In First class I want to use methods from Second class. So:
Java Code:
Second s = new Second(); s.secondMethod(); mh_sh_highlight_all('java');
Second thing I want to do is use JTextArea from First class in Second class.
So since it gives me error, I extended First class with Second:
Java Code: public class Second extends First { mh_sh_highlight_all('java');
It look like it should work, no errors etc. Also both things are working separately. But since I used both at once...
Java Code:
Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError at package.Second.<init>(Second.java:7) at package.First.<init>(First.java:17) mh_sh_highlight_all('java');
I can move what I need to First class, and it will work fine, but I want to make this in two classes. But I really don't understand extends, I just use them if there is need for them. So I don't know how to handle this problem.
I also tried to extends Second just like First:
Java Code: public class Second extends JPanel implements ActionListener { mh_sh_highlight_all('java');
Instead of extending First, but it can not be done, since ActionListener is in First...
Well. Also addActionListener can maybe solve my problem?
I have a folder of classes that I am packaging together. Some classes are being packaged and compiling just fine. My other classes in the same package, however, are saying that they cannot find these classes.
What i'm trying to do is to pass a bufferedreader string from main method to a class that will set on how fast or slow a message will be displayed but it has to be displayed on a JTextArea that's in a constructor class.
import java.awt.*; import javax.swing.*; public class demo { JFrame frame = new JFrame ("Idle Game Test!"); JPanel backGroundPanel = new JPanel (); JPanel statusPanel = new JPanel (); JPanel buttonPanel = new JPanel (); JPanel bigPanel = new JPanel (); JTextArea message = new JTextArea ();
So I prefer to use Emacs rather than using Eclipse or some other IDE and I am wondering how to include external classes in my main file?
For instance I have my main file (the one that includes my 'main()' function) and then I have another class (seperate file(s)) for creating a GUI, or making a game and using a Player class, Weapon class, etc. How can this be done? Do I just use 'extends myclass'?
I have been using Guice for a while but just now run into a need to use anonymous inner classes. In the example below Car and its dependencies do not get injected resulted in NPE on consecutive calls. How can this be changed to work properly? Do I need to add extra binding?
public class Truck { @Inject public Truck(Engine engine) { this.engine = engine; } public Car getCar() {
Is it possible to combine two classes that I have defined to contain some of the same elements so that NetBeans stops giving me errors? I don't want to get rid of any necessary code, and if both classes are necessary, should I just rename one of them? One class is an ArrayList that I am using to write the information for employees entered to a text file "employee.txt." I also want users to be able to call on this information via employeeID in order to display employee information. The code is the following:
public ArrayList<Employee> getEmployees() { // if the employees file has already been read, don't read it again if (employees != null) return employees; employees = new ArrayList<>(); if (Files.exists(employeesPath)) // prevent the FileNotFoundException {
[code]....
The other class is a getEmployee class that I previously defined before attempting to read the information from the text file and display it in the console. It is as follows:
private void getEmployees() { try { // if the file doesn't exists, create it if (!Files.exists(employeesPath)) Files.createFile(employeesPath); BufferedReader in = new BufferedReader( new FileReader(employeesFile));