# 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(){}
}
Related
public class test extends AbstractTableModel {
public static void main(String[] args) {
}
public String valuePass(int rowIn)
{
String value = "open";
return value;
}
test(mdpTEST parentPanel) {
m_parentPanel = parentPanel;
}
...
}
import demo.test;
public class order{
public void new()
{
test blah = new test(null);
String text = blah.valuePass(0);
}
}
In the code above, "blah" should be referencing the class "test" which is public, however I'm told to change the visibility of "test()" to public as I get an error in the line: "test blah = new test(null);". I'm confused at why "public class test" is not being referenced by "blah" and how the second instance of "test()" is being utilized here. I appreciate any help in understanding this problem!
Two issues with the code that you have shown
1) You cannot have new() as method name as new it is a keyword
2) Line test blah = new test(null); is calling a constructor of a test class which is in a different package. So default visibility is applied to test(...) constructor in test class. And as per java visibility rule, you have to make it public to access it in a different package
Do these changes and your code should work fine
I cant understand whats wrong with my code. In this code i getting errors like this when im trying to assign a value to a variable within a class. Also System.out.println doesnt work in this classes:
1.Identifier expected
2.Unexpected token
3.Unknown class "windows"
public static void main(String[] args) {
}
class building{
int apart_num;
apart_num = 3;
}
class apartments{
double area;
int lightbulb;
int windows;
windows = 4;
}
interface construct_building{
}
interface construct_apartments{
}
You are declaring an instance member on one line :
int apart_num;
and then assign a value to it :
apart_num = 3;
The problem is that this is done outside a method, those statement can't be separated, you can't assign a variable previously declare outside a block statement so.
Do it in a one line (declaration and assignation) :
class building{
int apart_num = 3;
}
or with a constructor
class building{
int apart_num;
public building(){
apart_num = 3;
}
}
or in a block statement
int windows;
{ //a block statement
windows = 4;
}
Then, if this code is not a class, you need to do it.
public MyClass{
public static void main(String[] args){ ... }
...
class Building { //inner class (will exist only inside of a MyClass instance
}
static class Apartment { // a nested class, exist whitout a MyClass instance
}
}
class Level { //A class that have nothing to do with MyClass and that can not be public.
}
Where MyClass is the name of the file (MyClass.java)
I am trying to write base code for my program, where I want to make some authentication check before returning some information.
Here is a sample code of it,
//Man.java
package com.test;
import java.lang.reflect.Method;
public abstract class Man {
protected abstract String getPassword();
public final String getMailPassword(){
try{
Method method = getClass().getDeclaredMethod("getPassword");
System.out.println("this: " + this);
System.out.println("method: "+ method.toString());
//check something if all OK
return (String)method.invoke(this);
//else return null
}catch(Exception ex){
ex.printStackTrace();
}
return null;
}
}
//Boss.java
package com.test;
import com.test.Man;
public class Boss extends Man {
#Override
protected String getPassword() {
return "Boss'_password";
}
}
//Tester.java
package com.test;
import com.test.test2.Boss;
public class Tester {
public static void main(String arg[]){
//System.out.println(new Servent().getMailPassword());
System.out.println(new Boss().getMailPassword());
}
}
When I execute above code (Tester.java) It execute correctly (all the files in same package), and I get following output.
this: com.test.Boss#22509bfc
method: protected java.lang.String
com.test.Boss.getPassword() Boss'_password
But If I move then Boss.java to different package "test2", I get exception.
java.lang.IllegalAccessException: Class com.test.Man can not access a member of class com.test.test2.Boss with modifiers "protected"
at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:109)
at java.lang.reflect.AccessibleObject.slowCheckMemberAccess(AccessibleObject.java:261)
at java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:253)
at java.lang.reflect.Method.invoke(Method.java:599)
at com.test.Man.getMailPassword(Man.java:14)
at com.test.Tester.main(Tester.java:8)
this: com.test.test2.Boss#5a30cefd
method: protected java.lang.String com.test.test2.Boss.getPassword()
null
I have printed 'this' which gives this: com.test.test2.Boss#5a30cefd, but the exception detects the super class in this case Class com.test.Man can not access a member of class com.test.test2.Boss with modifiers "protected". I understood the exception, but I didn't understood why in second case it detected super class. Please if some one can help me to fix this out (I have need of having sub classes in different packages, I can't put them in same package)
Call method.setAccessible(true) before calling invoke()
I have code like below sample. in that I am telling the class_name to get package name. instead of this method, i need another logic to get the package name withoud telling the class_name directly.
package smk.jsf.bean;
public class test {
public static void main(String[] args) {
System.out.println(test.class.getPackage().getName());
//Is there any option like "this.class.getPackage().getName();" bz. i don't want use class_name direclty
}
}
Output : smk.jsf.bean
Thanks to everyone.
Finally I got solution below
package smk.jsf.bean;
public class test {
public static void main(String[] args) {
String className = new Object(){}.getClass().getPackage().getName();
System.out.println(className);
}
Not sure it will suit you but try sun.reflect.Reflection.getCallerClass(). This class is present in JDK.
It will return a Class instance of method caller. Then just getPackage(). It is really dangerous stuff but it lets you not to use the class name directly.
Example usage - create a method String getPackageName() which will get caller class and return package name and call it from main.
Or you can throw any throwable, catch it and parse that throwable's stack trace to get the target package name (really sick way).
I have two approaches.
You can add a field public static final PACKAGE_INFO = "%package%"; to each file. Then traverse your source directory, read the line with the package package someName and replace the %package%
Use a dynamic approach at runtime. I wrote a little example program.
public class PackageExample {
public static void main(String[] args) throws ClassNotFoundException {
Example e = new Example();
System.out.println(e.getPackage());
}
}
interface MetaInformation {
public String getPackage() throws ClassNotFoundException;
}
class InformationGatherer implements MetaInformation {
public String getPackage() throws ClassNotFoundException {
StackTraceElement[] ste = new Exception().getStackTrace();
if (ste.length < 2)
throw new IllegalStateException("StackTrace to small to determine package!");
String clazz = ste[1].getClassName();
Class<?> c = Class.forName(clazz);
String package_ = "";
Package p = c.getPackage();
if (p != null)
package_ = c.getPackage().getName();
return package_;
}
}
class Example implements MetaInformation {
private InformationGatherer ig = new InformationGatherer();
public String getPackage() throws ClassNotFoundException {
return ig.getPackage();
}
}
Not sure if this helps but you can use reflection
http://docs.oracle.com/javase/tutorial/reflect/
Similar question :
See Can you find all classes in a package using reflection?
If it's a static method.No.
You cannot use this in a static context,since main is static method.
If it is not a static method,
String name = this.getClass().getPackage().getName();
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.