I guarantee you this will be a very stupid question, but I am having a brain block and can not figure out how to fix this error. I am working in Java and trying to define a Enum.
public enum ShooterStatus{
OFF,EXTENDING,CONTRACTING,LOADED
}
This enum is defined within another class. When compiling, I get the following error:
Implicit super constructor Enum(String, int) is undefined for default constructor. Must define an explicit constructor
What am I missing here? Shouldn't an enum declaration just be that? (I am used to programming in C)
Containing class:
package org.usfirst.frc3777;
import edu.wpi.first.wpilibj.DoubleSolenoid;
import edu.wpi.first.wpilibj.SpeedController;
import edu.wpi.first.wpilibj.Timer;
public class Shooter {
public enum ShooterStatus{
OFF,EXTENDED,CONTRACTING,LOADED
}
SpeedController upperCont;
SpeedController lowerCont;
DoubleSolenoid dS;
Boolean isLoaded;
Boolean isRunning;
Timer mainTimer;
DoubleSolenoid.Value extend = DoubleSolenoid.Value.kForward;
DoubleSolenoid.Value compress = DoubleSolenoid.Value.kReverse;
DoubleSolenoid.Value off = DoubleSolenoid.Value.kOff;
String label = "Shooter";
private boolean wheelsRunning(){
return upperCont.get()>.5&&lowerCont.get()>.5;
}
public Shooter(SpeedController upperCont, SpeedController lowerCont, DoubleSolenoid dS){
this.upperCont = upperCont;
this.lowerCont = lowerCont;
this.dS = dS;
}
private void setExtendPiston(){
dS.set(extend);
}
private void setCompressPiston(){
dS.set(compress);
}
private void setOffPiston(){
dS.set(off);
}
public boolean startShootingThread(){
if(!isLoaded){
Log.info(label, "Shooter is not currently loaded in logic");
return false;
}
if(isRunning){
Log.info(label, "Shooter is currently running");
return false;
}
setExtendPiston();
}
}
Get rid of the semicolon. Go from this:
public enum ShooterStatus{ OFF,EXTENDING,CONTRACTING,LOADED; }
to this:
public enum ShooterStatus{ OFF,EXTENDING,CONTRACTING,LOADED }
More info here.
You should also check if you ever defined a default JDK.
Related
# EvenDriver.java
package com.EventDrivenScenario.SystemElements;
import com.EventDrivenScenario.Exceptions.TableFullException;
import java.util.Random;
public class Table {
static final int TABLE_SIZE = 6;
static int tableCurrentSize;
Table(){
}
public static void main(String args[]){
Random eventTrigger = new Random();
while(true){
try {
if(eventTrigger.nextLong()%2 == 0){
new HumanBeing();
}
if (tableCurrentSize == TABLE_SIZE) {
throw new TableFullException();
}
} catch(TableFullException e) {
System.out.println(e.getMessage());
break;
}
}
}
}
class HumanBeing{
HumanBeing(){
new Chairs();
}
}
class Chairs{
Chairs(){
Table.tableCurrentSize++;
}
}
# TableFullException
package com.EventDrivenScenario.Exceptions;
public class TableFullException extends Exception{
TableFullException(){
}
public String getMessage() {
return ("Table Full - No More Visitors");
}
}
In the above code when i try to compile #EventDriver.java, I am getting compile time error indicating that TableFullException is not public and cannot be accessed outside package in spite of declaring it as public.
but if I change the package statement in both files to ##package com.EventDriver;## It works fine. I just want to understand why the above code throwing compile time error in spite of provide public access specifier for TableFullException.
Your TableFullException constructor is not public, so you can't create an instance of that exception from a class that doesn't belong to the same package. Make the constructor public, and your problem will be solved.
This is because you have a package private constructor for the class.
You have defined a constructor as package private by not giving any access modifier to the constructor Example :
public class PackagePrivateClassConstructor{
PackagePrivateClassConstructor(){}
}
You can use this constructor in the same package but outside the package it won't allow you to use it.
This is true for all you class Table,Chairs & HumanBeing.
You need to change it to
public class MyClass{
public MyCLass(){}
}
So I have small interface
public interface IPlayersStorage
{
// other methods...
public boolean addException(final String nick);
// other methods...
}
and class "PlayersStorage" that implements it: (only used part)
public class PlayersStorage implements IPlayersStorage
{
private static final PlayersStorage inst = new PlayersStorage();
private final Set<String> exceptions = new HashSet<>(50);
#Override
public boolean addException(final String nick)
{
return ! this.exceptions.add(nick);
}
public static PlayersStorage getStorage()
{
return inst;
}
}
And in some place I use that method using that code:
for (final String player : this.cfg.getStringList("Exceptions"))
{
PlayersStorage.getStorage().addException(player);
}
And ProGuard change it to:
for (Iterator localIterator1 = this.cfg.getStringList("Exceptions").iterator(); localIterator1.hasNext();)
{
localIterator1.next();
PlayersStorage.getStorage(); // it's get object, but don't do anything with it...
}
The only possible fix that I found, is add static method to PlayersStorage
public static boolean staticAddException(final String nick)
{
return inst.addException(nick);
}
And then use it (instead of old code)
for (final String player : this.cfg.getStringList("Exceptions"))
{
PlayersStorage.staticAddException(player);
}
Then works... (ProGuard keep method call) but adding static methods for every method from interface isn't good idea.
ProGuard only removes method invocations if they don't have any effect (doesn't seem to be the case here), or if you have specified -assumenosideffects for the methods. You should check your configuration and remove any such option.
Alternatively, your decompiler may be having problems decompiling the code. You should then check the actual bytecode with javap -c.
For my programming class in first year engineering I have to make a D-game in Java, with only very little knowledge of Java.
In one class I am generating a random integer via
public int rbug = (int)(Math.random() * 18);
every so many ticks. I have to use this integer in another class (in the requirements for an if-loop), and apparently it needs to be static. But when I change the variable to public int static, the value doesn't change any more.
Is there an easy way to solve this problem?
Edit: part of code added:
public int rbug = (int)(Math.random() * 18);
which is used in
public void render(Graphics g){
g.drawImage(bugs.get(rbug), (int)x, (int)y, null);
And in another class:
if(Physics.Collision(this, game.eb, i, BadBug.rbug)){
}
As error for BadBug.rbug I get the message
Cannot make a static reference to a non-static field
Using static to make things easier to access is not a very good ideal for design. You would want to make variables have a "getter" to access them from another class' instance, and possibly even a "setter". An example of this:
public class Test {
String sample = 1337;
public Test(int value) {
this.sample = value;
}
public Test(){}
public int getSample() {
return this.sample;
}
public void setSample(int setter) {
this.sample = setter;
}
}
An example of how these are used:
Test example = new Test();
System.out.println(example.getSample()); // Prints: 1337
example = new Test(-1);
System.out.println(example.getSample()); // Prints: -1
example.setSample(12345);
System.out.println(example.getSample()); // Prints: 12345
Now you might be thinking "How do I get a string from the class that made the instance variable within the class?". That's simple as well, when you construct a class, you can pass a value of the class instance itself to the constructor of the class:
public class Project {
private TestTwo example;
public void onEnable() {
this.example = new TestTwo(this);
this.example.printFromProject();
}
public int getSample() {
return 1337;
}
}
public class TestTwo {
private final Project project;
public TestTwo(Project project) {
this.project = project;
}
public void printFromProject() {
System.out.println(this.project.getSample());
}
}
This allows you to keep single instances of classes by passing around your main class instance.
To answer the question about the "static accessor", that can also be done like this:
public class Test {
public static int someGlobal = /* default value */;
}
Which allows setting and getting values through Test.someGlobal. Note however that I would still say that this is a horrible practice.
Do you want to get a new number every time that you want BadBug.rbug? Then convert it from a variable to a method.
I asked this question but I thought maybe this should be a separate question. Given the following class. Is this the best way to handle interface specific method calls based on a enum type? Thanks
#Component
public class HelloWorldImpl implements HelloWorld {
private enum MyEnum{
WALK,RUN,JOG,SKIP
}
#Autowired
#Qualifier("walkService")
private ActivityService walkService;
#Autowired
#Qualifier("runService")
private ActivityService runService;
#Override
public void executeMe(){
MyEnum myEnum = MyEnum.WALK;
for(MyEnum enum : MyEnum.values()){
switch(enum){
case RUN:
runService.execute();
case WALK :
walkService.execute();
etc....
}
}
}
}
I was trying to determine if there was a way I could just use the interface (i.e. ActivityService) to call the execute method instead of being specific to the "MODE" (i.e. switch / if). I was just thinking about what happens if I add a new "MODE" I will have to remember to add a section to this switch statement. Any help is greatly appreciated.
*Update
This exact pattern is suggested here.
I doubt you can make it any better. Well, you could by using the Factory pattern, but that seems to be overkill here.
Take a look at : http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/Calendar.java#Calendar.getInstance%28java.util.Locale%29
They use If statements in there. Seems like your code goes one better.
In order to evolve code in a factory scenario :
a) Caller has to know something about the "kind" of concrete implementation needed
b) For each "kind" of service a subclass is needed
Perhaps the only thing to criticize in your implementation is that the "kind" is hidden by a HelloWorldImpl that "knows" which service to return. Its probably more explicit to use subclasses directly because the method "executeMe" says nothing about what kind of service will be chosen at runtime (it depends on the enum).
You'd better add a method to the enum itself:
private enum MyEnum {
WALK {
#Override
public void execute() {
...
}
},
RUN {
#Override
public void execute() {
...
}
}
public abstract void execute();
}
That way, there(s no way you can add a new enum value without implementing its associated execute() method.
And the method becomes:
public void executeMe(){
MyEnum myEnum = MyEnum.WALK;
myEnum.execute();
}
You don't need such switch statement :)
#Override
public void executeMe(){
runService.execute();
}
All you need to is just call method on the interface. And JVM will run whichever implementation is already assigned to your service variable. That is the beauty of interfaces and exact reason they exist for.
Define a mapping of enumKey => concreteActivityServiceBean;
something like this in your spring app context:
<util:map id="activityServiceMapping" key-type="java.lang.String" value-type="com.somePackage.ActivityService" map-class="java.util.HashMap">
<entry key="RUN" value-ref="runServiceImpl" />
<entry key="WALK" value-ref="walkServiceImpl" />
</util:map>
#Component("runServiceImpl")
class RunServiceImpl implements ActivityService {
#Override
public void execute(){ ... }
}
#Component("walkServiceImpl")
class WalkServiceImpl implements ActivityService {
#Override
public void execute(){ ... }
}
And conditionally select the implementation to execute:
#Component
class HelloWorldImpl implements HelloWorld {
#Resource(name = "activityServiceMapping")
private Map<String, ActivityService> activityServices;
#Override
public void executeMe() {
ActivityService activityService = activityServices.get("WALK"); // or "RUN" or use the ENUM values....
activityService.execute();
}
}
I think you should try to refactor your class, so you only need one instance of the ActivityService class. Your code would then look something like this:
#Component
public class HelloWorldImpl implements HelloWorld {
private enum MyEnum{
WALK,RUN,JOG,SKIP
}
#Autowired
private ActivityService activityService;
#Override
public void executeMe(){
MyEnum myEnum = MyEnum.WALK;
activityService.execute(myEnum);
}
}
But it is hard to say whether this is a viable option, without knowing more about the responsibilities of ActivityService.
Or if you really just want the runner class to execute on the correct type every time without using DI or any class selection code or ifs or switch, then ensure that the correct class is instantiated prior to executing it.
ActionExecutor actionExecutor = (ActionExecutor)Class.forName("com.package.name." + action.name()).newInstance();
actionExecutor.execute();
Voila! Problem solved as long as you have a class for every possible action and those classes have a default constructor.
I had faced a similar problem. I found a solution that is more generic that the accepted answer.
The first step is to create an Interface.
public interface ActivityExecutor {
public void execute();
}
Now, all the required classes to execute must implement this class
public class WalkExecutor implements ActivityExecutor {
#Autowired
private WalkService walkService;
public void execute(){
walkService.execute();
}
}
public class RunExecutor implements ActivityExecutor {
#Autowired
private RunService runService;
public void execute(){
runService.execute();
}
}
Now the enums are declared in the following way
private enum MyEnum {
WALK {
#Override
public String getClassName() {
return "com.basepackage.WalkExecutor";
}
},
RUN {
#Override
public String getClassName() {
return "com.basepackage.RunExecutor";
}
}
public abstract String getClassName();
}
In the processing part, do the following.
String className = MyEnum.WALK.getClassName();
Class<?> clazz = Class.forName(className);
private static ApplicationContext appContext;
ActivityExecutor activityExecutor = (ActivityExecutor) appContext.getBean(clazz);
activityExecutor.execute(); // executes the required Service
Another way of fixing this problem could be:
public enum ExecutorType {
WALK, RUN
}
interface Executor {
void execute();
ExecutorType type();
}
Here we are able to do DI and create CDI/Spring Bean
final class WalkExecutor implements Executor {
#Override
public void execute() {
/** some logic **/
}
#Override
public ExecutorType type() {
return ExecutorType.WALK;
}
}
then we can access valid executor for given type.
public final class ExecutorService {
private final Map<ExecutorType, Executor> executorMap;
ExecutorService(List<Executor> executors) {
this.executorMap = executors.stream().collect(Collectors.toMap(Executor::type), Function.identity()));
}
public void execute(ExecutorType type) {
executorMap.get(type).execute();
}
}
Additionally we can ensure that every Executor type is implemented using either integration test or configuration class.
Configuration class using Spring:
#Configuration
class ExecutorConfiguration {
/** other beans definition **/
#Bean
ExecutorService executorService(List<Executor> executors) {
if (!allExecutorsImplemented(executors)) {
throw new RuntimeException("Invalid executor configuration");
}
return new ExecutorService(executors);
}
private boolean allExecutorsImplemented(List<Executor> executors) {
return executors.stream().map(Executor::type).distinct().count() == ExecutorType.values().length;
}
}
Scenario is like this:
There is a field in database 'overAllCount' which contains some value.
I have to use this variable in many classes I am designing.
I want to fetch this 'overAllCount' in one class say 'OverAllCountClass' and use it in all subclasses with its class name like OverAllCountClass.overAllCount. Basically like a static variable.
How can I do it?
My solution is:
public Class OverAllCountClass {
public static int OverAllCount;
public OverAllCountClass(){
// Fetch overAllCount from database here and set its value
}
}
////////// Use it like this //////////////
public class Usecount {
public void abc(){
// BUT IT IS NOT POSSIBLE becuase OverAllCountClass is not yet initialize
int mycount = OverAllCountClass.overAllCount
}
}
How can I achieve this?
If your concern is, the static variable overAllCount, might not get initialized and if you want it to get initialized whenever the class OverAllCountClass first gets invoked, then you can use Static initializer blocks
public class OverAllCountClass {
public static int overAllCount;
static {
overAllCount = fetchOverAllCount();
}
}
A static initializer block is invoked first time a class gets loaded. And a class gets first loaded when JVM sees that its been used.
public class Usecount {
public void abc(){
//When JVM sees that OberAllCountClass is used here, it executes the static block of OverAllCountClass and by the time below statement is executed, overAllCount is initialized
int mycount = OverAllCountClass.overAllCount
}
}
public Class OverAllCountClass {
protected int overAllCount; //will allow you to use in subclass too
public OverAllCountClass(){
// Fetch overAllCount from database here and set its value
}
public int getOverAllCount(){
return overAllCount;
}
}
public class Usecount {
//pass the instance of overAllCountInstance to UseCount somehow using constructor or setter
private OverAllCountClass overAllCountInstance;
public void abc(){
int mycount = overAllCountInstance.getOverAllCount();
}
}
No need to use static over here. Use getter to get the count
Rather than having a public static variable which can be modified/abused by other classes. I would provide a specific API which can hide the implementation and do things like lazy-loading if needed:
public static final Value getValue(){
//evaluate private field
return value;
}
This API can be a static method or be a singleton scoped method, depending on use case.
Another option is to make OverAllCountClass a Singleton.
public class OverAllCountClass {
private static final OverAllCountClass instance = new OverAllCountClass();
private Integer overAllCount = null;
// make it non-instanciable outside by making the constructor private
private OverAllCountClass {
}
public static OverAllCountClass getInstance() {
return instance;
}
public int getOverAllCount() {
if (overAllCount = null) {
//get value from database and assign it
}
return overAllCount;
}
}
This has the benefit that to code that accesses OverAllCountClass it is transparent wether it's a Singleton or not. This makes swapping out the implementation easier.