Java function (method) available everywhere (global) - java

I've recently (4 days ago) started programming in JAVA. I have some overall programming experience from C++ and PHP. My question is: can we implement a function in JAVA, that is available in all classes? I'm thinking of some global logging function, that I need to call in several places (log events, errors, etc.).
Imagine I have two classes, A and B. I need to call logging function in both of them, but I don't want to copy whole function body (awful thing I believe), and I want to call it strict (without creating another class, instantiating it, and then calling from the instance), like logEvent(someVariable). So I should use an abstract class C, which A and B will extend, BUT they are already an extension of other class (built-in). Since multiple inheritance isn't allowed (is it?), I need to do some trick. Singleton is not pleasing me too. In PHP or C++ I would just create separate file with function body and then include it.
Here is how I want to use it:
public class A extends SomeClass {
String error = "Error from class A";
logEvent(error);
}
public class B extends SomeOtherClass {
String error = "Error from class B";
logEvent(error);
}

Put a static method in any class (it could be a utils class, or whatever), then call it like this: ClassName.functionName()
Static methods belong to the class, not instances of the class, so you don't need to instantiate the class to access the method
But everything in Java has to be in a class, so you can't access it without the class name.

You should use static method:
package xxx;
public class Util{
public static void logEvent(String error){
...
}
}
and import static:
import static xxx.Util.*;
public class A extends SomeClass {
String error = "Error from class A";
logEvent(error);
}

You may use static method.
Define a class with a static method:
public class Util{
public static void logEvent(String error){
...
}
}
Then, you can use static metod like this way:
public class A extends SomeClass {
String error = "Error from class A";
Util.logEvent(error);
}
you may take a look here to learn more about static method, http://www.leepoint.net/notes-java/flow/methods/50static-methods.html

Related

accesing static class static member from another namespace generates: no such reference error

I am writting a specialistic control that involves an own widget-system (...because I must - I am working with raster graphics, so I decided to not use the standard buttons).
I encountered a problem with accessing a static member of a static sub-class that isn't in the name space that I call it from. By what I think - this reference should work without problems, as the static class, and static method both have the public qualifier.
The code is somehow like this:
//SpecializedView.java
public class SpecializedView extends View
{
...
button.controler_group[] controler_group;
button button1;
public void init()
{
button_group=button.controler_group.generate_group(8);//generates the error message
button1=new button(controler_group);
}
...
}
//button.java
public class button extends button_specialization
{
...
//EDIT[
controler_group[]controler_group;
//]
public button(controler_group[]controler_group)
{
this.controler_group=controler_group;
...
}
static public class controler_group
{
static public controler_group[] generate_group(int size){...}
...
}
...
}
I have another project with similar structure and it works well (involving calling the static sub-class static member), it only doesn't involve interaction with the class-object itself (it's a pure static function that works as a namespace-library function). I thought the case may be generation of the array, but the result was identical with any sort of returned value.
Could you be more precise with the members of the classes. The error you specified mean that you have no member of this name, or that it's by some means unaccesible. As the member you are trying to access (and by the suggestion made in your code).
There is a chance that the compiler understands that you are trying to access a static member of the parent class, that is probably an instance of the class with the same name as the class definition.

Java - Declare Class Once Use Anywhere

Very simple problem but im not understanding static correctly.
I have java file which holds my main and its call testMain.
With my testMain it makes many classes with use other classes.
E.g. testMain>>GUI and testMain>>model and testMain>>controller
Now i have a class called generatorTester which i would like to declare once like:
public static utils.generatorTester randomGen = new utils.generatorTester ();
(utils is my custom package for my common classes)
Why does the above line not aloud me to do the following
classNameOfMainFunction.randomGen
Im i programming wrong here? Is this even possbile.
I bassicly want to make the class globably and use it any where.
A public static field of a public class can be used anywhere, you just need to use the right syntax to access it.
If you declare:
package foo;
public class Global {
public static Some thing;
}
And do
import foo.Global;
you can access the field with
Global.thing
Alternatively, you can do
import static foo.Global.thing;
and access it with
thing
About the best you can get is this:
public abstract class GloballyUsed {
public static int method() { return 4;
/* determined by fair
* dice roll, guaranteed to be random */
}
and:
GloballyUsed.method();
to call elsewhere.
Note per comment (I just learned this) since Java 5 you can import just a specific method name as:
import static {package}.GloballyUsed.method;
Note I added the keyword abstract, this is to further convince you that you never actually instantiate GloballyUsed. It has no instances. You probably have some reading to do on what static means.

Calling method without object

I have built a small (and 3 methods only!) api for myself, and I want to be able to call it like how you would call a method in Powerbot (A Runescape botting tool (I use it, but for programming purposes, not for actual cheating purposes)), without creating an Object of the file you'd require. How would i be able to do this?
You will need to create static methods, so you will need to do something like so:
public class A
{
public static void foo()
{
...
}
}
And then, you can call them like so:
public class B
{
...
A.foo();
}
Note however that static methods need to be self contained.
EDIT: As recommended in one of the answers below, you can make it work like so:
package samples.examples
public class Test
{
public static void A()
{
...
}
}
And then do this:
import static sample.examples.Test.A;
public class Test2
{
...
A();
}
If you use the static keyword when importing your class, you can use its methods as if they belong to the class you're importing them to. See:
http://docs.oracle.com/javase/1.5.0/docs/guide/language/static-import.html
And of course your "api methods" need to be static as well.
The best way i found out for me was to extend my activity (If i said it right)...
MAIN CLASS
public class myMainActivity extends myMiniApi{
...
}
I think this is a better way (my opinion) to do this, Just call your method like you normally would as if it were in the same class. example:
randomMethod();

Java: reusable encapsulation with interface, abstract class or inner classes?

I try to encapsulate. Exeption from interface, static inner class working, non-static inner class not working, cannot understand terminology: nested classes, inner classes, nested interfaces, interface-abstract-class -- sounds too Repetitive!
BAD! --- Exception 'illegal type' from interface apparently because values being constants(?!)
static interface userInfo
{
File startingFile=new File(".");
String startingPath="dummy";
try{
startingPath=startingFile.getCanonicalPath();
}catch(Exception e){e.printStackTrace();}
}
MANY WAYS TO DO IT: Interface, static inner class image VS non-static innner class image
import java.io.*;
import java.util.*;
public class listTest{
public interface hello{String word="hello word from Interface!";}
public static class staticTest{
staticTest(){}
private String hejo="hello hallo from Static class with image";
public void printHallooo(){System.out.println(hejo);}
}
public class nonStatic{
nonStatic(){}
public void printNonStatic(){System.out.println("Inside non-static class with an image!");}
}
public static class staticMethodtest{
private static String test="if you see mee, you printed static-class-static-field!";
}
public static void main(String[] args){
//INTERFACE TEST
System.out.println(hello.word);
//INNNER CLASS STATIC TEST
staticTest h=new staticTest();
h.printHallooo();
//INNER CLASS NON-STATIC TEST
nonStatic ns=(new listTest()).new nonStatic();
ns.printNonStatic();
//INNER CLASS STATIC-CLASS STATIC FIELD TEST
System.out.println(staticMethodtest.test);
}
}
OUTPUT
hello word from Interface!
hello hallo from Static class with image
Inside non-static class with an image!
if you see mee, you printed static-class-static-field!
Related
Nesting classes
inner classes?
interfacses
The problem is that you're writing code outside of a method. You do need a class for this and you must put your code inside a method. For example:
static class UserInfo
{
public static void myMethod()
{
File startingFile = new File(".");
String startingPath = "dummy";
try
{
startingPath = startingFile.getCanonicalPath();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
This does assume that java.io.File was imported.
You can then call UserInfo.myMethod();
You might also want to import java.util.IOException and catch an IOException instead of a general Exception.
Also, classes and interfaces start with a capital letter by Java conventions.
EDIT: To describe your recent comment on your question:
Use an interface when you want to force similar classes (Think different types of DVD players) to have the same basic functionality (playing dvds, stopping, pausing. You use an abstract class similarly, but when all of the classes will implement some of the same things the same way.
I think you wanted to do this:
static class userInfo
{
public static void something() {
File startingFile=new File(".");
String startingPath="dummy";
try{
startingPath=startingFile.getCanonicalPath();
}catch(Exception e){e.printStackTrace();}
}
}
you cant put code in an interface, an interface only describes how an object will behave. Even when you use Classes, you should put this kind of code in a method, and not directly in the class body.
You can't have actual code in an interface, only method signatures and constants. What are you trying to do?
Looks like you want to write a class here.
You cannot have code in interfaces. Just method signatures.
Top level interfaces cannot be static.
I suggest you start your learning of Java here.

Interfaces in Java: cannot make implemented methods protected or private

I know that an interface must be public. However, I don't want that.
I want my implemented methods to only be accessible from their own package, so I want my implemented methods to be protected.
The problem is I can't make the interface or the implemented methods protected.
What is a work around? Is there a design pattern that pertains to this problem?
From the Java guide, an abstract class wouldn't do the job either.
read this.
"The public access specifier indicates that the interface can be used by any class in any package. If you do not specify that the interface is public, your interface will be accessible only to classes defined in the same package as the interface."
Is that what you want?
You class can use package protection and still implement an interface:
class Foo implements Runnable
{
public void run()
{
}
}
If you want some methods to be protected / package and others not, it sounds like your classes have more than one responsibility, and should be split into multiple.
Edit after reading comments to this and other responses:
If your are somehow thinking that the visibility of a method affects the ability to invoke that method, think again. Without going to extremes, you cannot prevent someone from using reflection to identify your class' methods and invoke them. However, this is a non-issue: unless someone is trying to crack your code, they're not going to invoke random methods.
Instead, think of private / protected methods as defining a contract for subclasses, and use interfaces to define the contract with the outside world.
Oh, and to the person who decided my example should use K&R bracing: if it's specified in the Terms of Service, sure. Otherwise, can't you find anything better to do with your time?
When I have butted up against this I use a package accessible inner or nested class to implement the interface, pushing the implemented method out of the public class.
Usually it's because I have a class with a specific public API which must implement something else to get it's job done (quite often because the something else was a callback disguised as an interface <grin>) - this happens a lot with things like Comparable. I don't want the public API polluted with the (forced public) interface implementation.
Hope this helps.
Also, if you truly want the methods accessed only by the package, you don't want the protected scope specifier, you want the default (omitted) scope specifier. Using protected will, of course, allow subclasses to see the methods.
BTW, I think that the reason interface methods are inferred to be public is because it is very much the exception to have an interface which is only implemented by classes in the same package; they are very much most often invoked by something in another package, which means they need to be public.
This question is based on a wrong statement:
I know that an interface must be public
Not really, you can have interfaces with default access modifier.
The problem is I can't make the interface or the implemented methods protected
Here it is:
C:\oreyes\cosas\java\interfaces>type a\*.java
a\Inter.java
package a;
interface Inter {
public void face();
}
a\Face.java
package a;
class Face implements Inter {
public void face() {
System.out.println( "face" );
}
}
C:\oreyes\cosas\java\interfaces>type b\*.java
b\Test.java
package b;
import a.Inter;
import a.Face;
public class Test {
public static void main( String [] args ) {
Inter inter = new Face();
inter.face();
}
}
C:\oreyes\cosas\java\interfaces>javac -d . a\*.java b\Test.java
b\Test.java:2: a.Inter is not public in a; cannot be accessed from outside package
import a.Inter;
^
b\Test.java:3: a.Face is not public in a; cannot be accessed from outside package
import a.Face;
^
b\Test.java:7: cannot find symbol
symbol : class Inter
location: class b.Test
Inter inter = new Face();
^
b\Test.java:7: cannot find symbol
symbol : class Face
location: class b.Test
Inter inter = new Face();
^
4 errors
C:\oreyes\cosas\java\interfaces>
Hence, achieving what you wanted, prevent interface and class usage outside of the package.
Here's how it could be done using abstract classes.
The only inconvenient is that it makes you "subclass".
As per the java guide, you should follow that advice "most" of the times, but I think in this situation it will be ok.
public abstract class Ab {
protected abstract void method();
abstract void otherMethod();
public static void main( String [] args ) {
Ab a = new AbImpl();
a.method();
a.otherMethod();
}
}
class AbImpl extends Ab {
protected void method(){
System.out.println( "method invoked from: " + this.getClass().getName() );
}
void otherMethod(){
System.out.println("This time \"default\" access from: " + this.getClass().getName() );
}
}
Here's another solution, inspired by the C++ Pimpl idiom.
If you want to implement an interface, but don't want that implementation to be public, you can create a composed object of an anonymous inner class that implements the interface.
Here's an example. Let's say you have this interface:
public interface Iface {
public void doSomething();
}
You create an object of the Iface type, and put your implementation in there:
public class IfaceUser {
private int someValue;
// Here's our implementor
private Iface impl = new Iface() {
public void doSomething() {
someValue++;
}
};
}
Whenever you need to invoke doSomething(), you invoke it on your composed impl object.
I just came across this trying to build a protected method with the intention of it only being used in a test case. I wanted to delete test data that I had stuffed into a DB table. In any case I was inspired by #Karl Giesing's post. Unfortunately it did not work. I did figure a way to make it work using a protected inner class.
The interface:
package foo;
interface SomeProtectedFoo {
int doSomeFoo();
}
Then the inner class defined as protected in public class:
package foo;
public class MyFoo implements SomePublicFoo {
// public stuff
protected class ProtectedFoo implements SomeProtectedFoo {
public int doSomeFoo() { ... }
}
protected ProtectedFoo pFoo;
protected ProtectedFoo gimmeFoo() {
return new ProtectedFoo();
}
}
You can then access the protected method only from other classes in the same package, as my test code was as show:
package foo;
public class FooTest {
MyFoo myFoo = new MyFoo();
void doProtectedFoo() {
myFoo.pFoo = myFoo.gimmeFoo();
myFoo.pFoo.doSomeFoo();
}
}
A little late for the original poster, but hey, I just found it. :D
You can go with encapsulation instead of inheritance.
That is, create your class (which won't inherit anything) and in it, have an instance of the object you want to extend.
Then you can expose only what you want.
The obvious disadvantage of this is that you must explicitly pass-through methods for everything you want exposed. And it won't be a subclass...
I would just create an abstract class. There is no harm in it.
With an interface you want to define methods that can be exposed by a variety of implementing classes.
Having an interface with protected methods just wouldn't serve that purpose.
I am guessing your problem can be solved by redesigning your class hierarchy.
One way to get around this is (depending on the situation) to just make an anonymous inner class that implements the interface that has protected or private scope. For example:
public class Foo {
interface Callback {
void hiddenMethod();
}
public Foo(Callback callback) {
}
}
Then in the user of Foo:
public class Bar {
private Foo.Callback callback = new Foo.Callback() {
#Override public void hiddenMethod() { ... }
};
private Foo foo = new Foo(callback);
}
This saves you from having the following:
public class Bar implements Foo.Callback {
private Foo foo = new Foo(this);
// uh-oh! the method is public!
#Override public void hiddenMethod() { ... }
}
I think u can use it now with Java 9 release. From the openJdk notes for Java 9,
Support for private methods in interfaces was briefly in consideration
for inclusion in Java SE 8 as part of the effort to add support for
Lambda Expressions, but was withdrawn to enable better focus on higher
priority tasks for Java SE 8. It is now proposed that support for
private interface methods be undertaken thereby enabling non abstract
methods of an interface to share code between them.
refer https://bugs.openjdk.java.net/browse/JDK-8071453

Categories