Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I would like to inherrit the rooms variable just as foo is being inherited. I have searched around google and stackoverflow but couldn't find relevant posts. It may be a short description of the question but I don't think anything more is needed.
Code
import java.util.ArrayList;
class HomeAbstraction { // HomeAbstraction = Rooms; It's named like this to fit the rest of the project
float area;
public HomeAbstraction(float area) {
this.area = area;
}
}
class Home {
String foo = "bar";
ArrayList < HomeAbstraction > rooms = new ArrayList < HomeAbstraction > ();
// setter
public void setRooms(HomeAbstraction rooms) {
this.rooms.add(rooms);
}
}
class Department extends Home {
// constructor
public Department() {
foo = "foo"; // works fine
rooms; // should be pulled from parent but isn't working
rooms.setRooms(new HomeAbstraction(50)); // Not sure if I can access the setter from this child class
}
}
Error log
idk.java:25: error: cannot find symbol
rooms.setRooms(new HomeAbstraction(50));
^
symbol: method setRooms(HomeAbstraction)
location: variable rooms of type ArrayList<HomeAbstraction>
1 error
You can try:
rooms.add(new HomeAbstraction(50));
or
super.setRooms(new HomeAbstraction(50));
or
super.rooms.add(new HomeAbstraction(50));
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am trying to learn object oriented code in Java, and am following a tutorial. I am currently stuck trying to parse a string into my class. It is returning the following error:
Name cannot be resolved to a variable
I have a main file, called start.java, and the class I am trying to call is in a different file, called phone.java. Both are in a folder called src. Below is the start.java code (which is throwing the error)
package src;
public class Start {
public static void main(String[] args){
phone android = new phone(Name:"android 10");
System.out.println(android.getName());
}
}
And here is the class I am trying to call, in phone.java
package src;
public class phone{
private String name;
public phone(String name) {
this.name = name;
}
public String getName(){
return this.name;
}
}
Much thanks for your help
You need to remove the Name from new phone(Name:"android 10") and need to use new phone("android 10").
You just need to pass the value for the name, your constructor will bind it to the name variable.
Refer below code
public class Start {
public static void main(String[] args){
phone android = new phone("android 10");
System.out.println(android.getName());
}
}
I asked a similar question to this recently, but I did a bad job at explaining it, so I am going to try again.
I cannot figure this out for the life of me. I have to do two different java files for this programming assignment, and when running the program from command prompt I get an error that says it cannot find symbol of when I create my object in the second class, and when I run the code in Eclipse I get the error "Error occurred during initialization of boot layer
java.lang.LayerInstantiationException: Package jdk.internal.jrtfs in both module jrt.fs and module java.base".
I even copied an example straight from the textbook to understand it, but it isn't working even though I have exactly what's in the textbook. The pastebin links are for the two classes that come from the textbook examples.
Please someone tell me what's wrong here.
First class: https://pastebin.com/KYHtDHPt
public class Account {
private String name;
public Account(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Second class: https://pastebin.com/ADUsjjaR
public class AccountTest {
public static void main(String[] args) {
Account account1 = new Account("Brandon Williams");
System.out.printf("Account one is: %s%n",account1.getName());
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
Can someone please explain how is possible, that method obtain(..) throws IllegalStateException for input ConfiguratorType.SKODA (the variable configurators contains {SKODA=null})? How can it be null, I do not understand why SkodaConfigurator.INSTANCE returns null. It should never be null or am i mistaken? The code is executed in servlet environment, Java 7.
Thank you
public class CarConfigurators {
private static Map<ConfiguratorType, CarConfigurator> configurators
= new EnumMap<ConfiguratorType, CarConfigurator>(ConfiguratorType.class);
static {
configurators.put(ConfiguratorType.SKODA, SkodaConfigurator.INSTANCE);
// ..
}
public static CarConfigurator obtain(ConfiguratorType type) {
CarConfigurator configurator = configurators.get(type);
if (configurator == null)
throw new IllegalStateException("Car configurator of type " + type + " is not registered.");
return configurator;
}
...
}
public class SkodaConfigurator extends CarConfigurator {
public static final SkodaConfigurator INSTANCE = new SkodaConfigurator();
...
}
public enum ConfiguratorType {
SKODA,
// ..
}
Static code cannot all run simultaneously, the various bits of static initialization going on have to happen in a given order. Clearly in this case, your static block which does configurations.put(...) is running before the static variable in SkodaConfiguration is initialized.
This is related to static initialization order.
I found this from another answer
public class Main {
{
System.out.printf("NON-STATIC BLOCK\n");
}
static{
System.out.printf("STATIC BLOCK\n");
}
public static Main m = new Main();
public Main(){
System.out.printf("MAIN CONSTRUCTOR\n");
}
public static void main(String... args) {
//Main m = new Main();
System.out.printf("MAIN METHOD\n");
}
}
Output :
STATIC BLOCK
NON-STATIC BLOCK
MAIN CONSTRUCTOR
MAIN METHOD
Please go through this : Java Static Initialization Order
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I want to have only 5 instance of a class throughout the application life time. How can I achieve this? Please give sample code, if possible.
As Singletons shall be made with enums (See "Effective Java"):
public enum FiveInstance {
INSTANCE1, INSTANCE2, INSTANCE3, INSTANCE4, INSTANCE5;
public void anyMethod() {}
}
Greetz GHad
The Factory pattern could be your friend. One (fictional, not threadsafe and thus quite simple) example to illustrate the approach:
public static MartiniFactory {
private static int olives = 100; // you asked for '5' but 100 is more realistic
// for this example.
public static Drink createMartini() throws OutOfOlivesException {
if (olives > 0) {
olives--;
return new Martini(new Gin(4), new Vermouth(1), new Olive());
else {
throw new OutOfOlivesException();
}
}
// forgot to mention, only the factory (=bar) is able to create Martinis, so:
private class Martini {
Martini(Ingredient... ingredients) {
// ...
}
// ....
}
}
EDIT
The license example was not too good - so I moved it to a domain that expects, that objects created by the factory are not returned and destroyed without noticing the factory. The Bar can't create Martinis when there is no olive left and it definitly doesn't want the drink back after it has been consumed ;-)
EDIT 2
And for sure, only the factory can create Instances (=Drinks).
(No guarantee, that the added inner private class fulfills this requirement, don't have
an IDE at hand to do a quick test .. feel free to comment or edit)
class Sample
{
private static int i = 0;
private Sample()
{
}
public static Sample CreateInstance()
{
if(i <5)
{
i++;
return new Sample();
}
else
throw new Exception("Can not create more then 5 instance of this class");
}
}
Have a look at the static keyword.
public class FiveInstance {
private static int instanceCount = 0;
private FiveInstance(){
}
public static FiveInstance getNewInstance() throws InstanceExceededException{
if(instanceCount < 5){
instanceCount++;
return new FiveInstance();
}else{
throw new InstanceExceededException();
}
}
}
Create a private static member to count the instances of the class. Then, make sure every constructor of your class increment this static variable and test for overflow. If you have more than one constructor I suggest that you make one constructor implement this behaviour and the others should call it. The behavior of the constructor upon an attempt to create a sixth instance is up to you. Maybe you want to throw an Exception.
You can try following code but written in C#, you can get a basic idea how can it be done.
public class MultiTone
{
private static MultiTone _cache;
private static int _counter=5;
MultiTone()
{
}
public static MultiTone GetInstance()
{
if(_counter==0)
{
return _cache ?? (_cache = new MultiTone());
}
_counter--;
return new MultiTone();
}
}
And mind that this class is't intended to use in multi-threading environment.
I think you can't. You can force that if somebody want to create or destroy an instance has to use these static methods:
import java.util.*;
public class Fiveton {
public final static int MAX_INSTANCES = 5;
private static List<Fiveton> instances = new ArrayList<Fiveton>();
private Fiveton() { }
public static Fiveton getInstance() {
if (instances.size()>=MAX_INSTANCES) throw new RuntimeException("Hey! You've reached the maximum of instances: " + MAX_INSTANCES);
Fiveton instance = new Fiveton();
instances.add(instance);
return instance;
}
public static void destroy(Fiveton instance) {
instances.remove(instance);
}
}
The problem is method destroy. You can't be sure that someone is still referencing the destroyed object.
There is a pattern called a Multiton which deals with this, as an extension of Singleton. Nobody seems quite clear it it's a pattern in its own right or a variation on Singleton. Check out the link, it includes sample code.
Look at Object pool pattern. Its java implementation is greatly described in Grand Patterns in Java V1.
Short description from the book overview:
Object Pool
Manage the reuse of objects for a type
of object that is expensive to create
or only a limited number of a kind of
object can be created.
Create a static field called howMany which will be incremented each time that the constructor is called.
When howMany is => 5, deny creation of the object.