How can I create a class with all my functions in java?
when I create functions (methods) in a class, I can't seem to use them in other class.
I would like to create a single class for all the impotent functions and call them from there
public class all_function(){
public int func1(...)
public int func2(...)
.
.
.
}
and than for all other classes, using those functions
public class main_app
function.func1(...)
when trying to do so I get an error indicating that the function is not declared etc.
thanks
#Quincunx's answer in the comments is correct, but writing whole programs like this violates all sorts of OO principles, and it's not a good idea for readability, maintainability, etc. You probably want to go back and read some basic Java tutorials.
For example, to use a method outside of the class that declares it, you need to create an instance of that object:
public class Foo {
public void doSomething() {
System.out.println("I did something!");
}
}
public class Bar {
public static void main(String[] args) {
Foo foo = new Foo();
foo.doSomething();
}
}
If you have a method that's not specific to the class that declares it (i.e., a utility class), though, then by all means declare it static:
public class Foo {
public static void doSomething() {
System.out.println("I did something!");
}
}
public class Bar {
public static void main(String[] args) {
Foo.doSomething();
}
}
Related
I'm trying to understand Java anonymous classes.
Looking here:
https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html
And here:
http://docstore.mik.ua/orelly/java-ent/jnut/ch03_12.htm
I understand the basic syntax, but the examples are non-minimal.
What are the absolute minimal requirements to define a anonymous class in Java?
Edit>>>
Essentially this:
public class MyClass {
InnerClass instance = new InnerClass();
public class InnerClass{
public void print(){
System.out.println("First Call");
}
};
public void redefineInstance(){
instance = new InnerClass(){
public void print(){
System.out.println("Second Call");
}
};
}
public static void main(String[] args) throws Exception{
MyClass myobject = new MyClass();
myobject.instance.print();
myobject.redefineInstance();
myobject.instance.print();
}
}
The most minimal example:
interface Foo {}
public static void main (String[] args)
{
Foo foo = new Foo() {};
}
Literally a declaration of an interface, and then usage as an anonymous class with no additional declarations.
Practically speaking, it does nothing. However, as we add bits in:
interface Foo {
public void bar();
}
public static void main (String[] args) throws java.lang.Exception
{
Foo foo = new Foo() {
public void bar() {
System.out.println("Hello");
}
};
}
It becomes a full-fledged helper class for our method.
The most common use for early/mid level programming would be overriding Listeners to do specific actions. We know the Listener is listening for something, and we want it to do something as a result of the Listener, so we craft the Listener and say "Do this when you are triggered."
Here's the example of a really complex ActionListener tutorial: https://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html
But typically, if it's something that's mundane like "run a method on click", you'll use an anonymous in-line declaration that just calls a method for you.
I suppose the "absolute minimal requirement" to create an anonymous class is to have a place in your code that requires an instance of a non-final class or interface of some kind.
Meaning, if I have a method in MyClass:
public static void gimmeMyObject(MyObject c)
I can define an anonymous class that extends MyObject as long as MyObject is not final:
//Somewhere in a method
MyClass.gimmeMyObject(new MyObject() {
public String myMethod() {
return "I'm anonymous";
}
});
That anonymous class will be passed in as a MyObject.
However, I could not do this if the method required a String or Integer, for example, because those are final classes.
For the above example, the non-anonymous class would translate to:
public class MyAnonObject extends MyObject { //In actuality, an anonymous class doesn't have a name, though.
public String myMethod() {
return "I'm anonymous";
}
}
As Compass has already said, the absolute minimum is not useful.
Following is an example of a 'useful' inner class:
JButton ok = new JButton();
ok.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("abc");
}
});
So instead of having to define an inner class or a helper class for an ActionListener you only use once, you can just have it as an inline or anonymous class to remove clutter and increase readability.
How about this example?
//interface
interface Message{
String greet();
}
Message is a anonymous class in this example,
greet() is the only method inside this anonymous class.
//Passing an anonymous inner class as an argument
obj.displayMessage(new Message(){
public String greet(){
return "Hello";
}
});
You can think of an anonymous class as just basically the instantiation part of creating a new instance of an object. You essentially just don't declare it and give it a name. This is normally passed into method parameters as shown below.
Object someObj; is an object declaration.
someObj = new Objct(parm a,...) is the instantiation of the object.
//example of anonymous classes:
public void foo(Bar barObj){// takes a Bar object parameter
//does stuff
}
//you can call the foo method in this way
Bar barObject= new Bar();
foo(barObject){}
// or you can call the Bar anonymously
foo(new Bar()){}
In the anonymous example you instantiate a new Bar inside the method parameter. You can do this when you just need something local and don't need it to be used anywhere but in that method call. it also then gives you access to the accessible methods that are inside of the anonymous class. so you could do something like
foo(new Bar().barMethod){}. It just kind of depends what you are working with.
I have seen this done in many programs but I cant seem to follow the programming logic.
Lets say you have a simple class, ClassB. And in ClassB's main method you define an integer variable:
public class B {
public static void main(String[] args) {
int stuff = 333;
}
}
How can you transfer the variable to a different class, say ClassA, to be used.
public class A {
public static void main(String[] args) {
System.out.println(stuff);
}
}
Can someone please explain this to me in simple terms. I've been trying to learn this for 2 hours and cant wrap my head around it.
public static void main(String[] args) is meant to be used as a starting point for a Java program. Probably it's better to rename one of your methods to something else.
The problem you are seeing, is that the scope of the variable int stuff is limited to the main() method of class B, because it is declared within the body of the main() method. In order to make it visible, you need to declare it as a public field (which can be static in your case).
I propose you change your program like follows:
public class A {
public static int stuff;
public static void initStaticMembers() {
stuff = 333;
}
}
public class B {
public static void main(String[] args) {
A.initStaticMembers();
System.out.println(A.stuff);
}
}
I renamed the main() method of A to initStaticMembers() and dropped the method parameters, since they are not needed in our case. In order to use the field A.stuff in B, the method A.initStaticMembers() needs to be called first.
Of course there are ways to improve this program, but I think you should learn Java one step at a time.
You shouldn't have 2 main methods. Only one class should (typically):
ClassA.java
public class A {
public static void main(String[] args) {
ClassB b = new ClassB();
System.out.println(b.stuff);
}
}
ClassB.java
public class B {
public int stuff = 333; // member variable
}
You instantiate the second class in the first one, then you're granted access to its public member variables.
I am trying to create an Anonymous class during which I came across following problem. In the following code when I change display method access modifier to default it gives an error but when I change it to public it works fine. Could you explain it to me why this happens.AFAIK public and default are work in similar as long as all classes are in same package. Please correct me if I am wrong.
//from file : Skg.java
package sandeep2;
class Skg1
{
public void display()
{
System.out.println("sandeep here");
}
}
class Skg2 {
public void say()
{
System.out.println("Skg2");
}
Skg1 obj = new Skg1()
{
**public void display()** //wont work if this is not public ????????????
{
System.out.println("I am ANONymous");
}
};
}
public class Skg {
public static void main(String[] args)
{
Skg2 x = new Skg2();
x.obj.display();
}
}
Class Skg2 attempts to create an instance of an anonymous inner class as a subclass of class Skg1. That anonymous inner class overrides Skg1.display(), which is public. You cannot override a method to reduce its visibility. Java does not permit it, and it would violate the substitution principle if you could do it.
I declared the following class
class A { //not public
public static void main(String args[]) {
System.out.println("done");
}
When I compile and run it, it runs fine and prints the output "done". Same behavior even when I declare it as being in a "package a;"
However, if JVM spec mandates that main method should be public since "it can't see main otherwise", shouldn't it apply to the class as well?
If the JVM "can't see" A.main() when it is not declared public, how is it able to see the class A itself.
Is there any explanation for this other than "because the specification says so"?
The JVM has access to every class in the application all the time because one of its responsibilities is enforcing visibility rules. Therefore, one can draw the conclusion that it can ignore visibility rules if need be (e.g. when the user starts the application, the JVM has to find the entry point, which is main()).
In other words, the JVM is not a class accessing this function, so visibility doesn't apply. It is basically the overseer, managing the application from execution to termination.
For reference, see Execution.
When you declare a class private, you're not making it "invisible", and the same goes for your methods. Declaring a method private simply means it's not callable from outside your class. A static public method of a private class is publicly callable.
The reason the JVM can see a non-public class is because it controls visibility, meaning it sees everything and decides what can see/call/access what.
The use of public on a class is different than on a method, but the concept is the same.
On a method, the public keyword means the method can be used outside the class. An example would be:
class A {
public static void do() {
// Do something
}
}
class B {
public static void main(String[] args) {
A.do(); // This works because do() is public and static
}
}
The same concept applies to classes, but in a different way.
Using public on a class means that it can be used outside the current .java file (it will have its own .class file).
Here's an example:
//C.java
class C {
static void do() {
// Do something
}
public static void run() {
A.do(); // Works because A.do() is public and static
B.do(); // Does not work because B is not a public class
}
}
//A.java
public class A {
public static void main(String[] args) {
B.do(); // Works because B is in the same file
do(); // Duh...
}
public static void do() {
// Do something
}
}
class B {
static void do() {
// Do something
}
}
I am trying to wrap my mind around something in java. When I pass an object to another class' method, can I not just call any methods inherent to that object class?
What is the reason code such as the example below does not compile?
Thank you,
class a {
public static void myMethod(Object myObj) {
myObj.testing();
}
}
class b {
public void testing() {
System.out.println ("TESTING!!!");
}
}
class c {
public static void main (String[] args) {
b myB = new b();
a.myMethod(myB);
}
}
Edit: The reason I have left the parameter in myMethod as type Object, is because I would like to be able to pass in a variety of object types, each having a testing() method.
If you would like to pass in a variety of objects with testing() methods, have each object implement a Testable interface:
public interface Testable
{
public void testing()
}
Then have myMethod() take a Testable.
public static void myMethod(Testable testable)
{
testable.testing();
}
Edit: To clarify, implementing an interface means that the class is guaranteed to have the method, but the method can do whatever it wants. So I could have two classes whose testing() methods do different things.
public class AClass implements Testable
{
public void testing()
{
System.out.println("Hello world");
}
}
public class BClass implements Testable
{
public void testing()
{
System.out.println("Hello underworld");
}
}
The problem is that myMethod can't know it's getting a b object until it actually runs. You could pass a String in, for all it knows.
Change it to
public static void myMethod(b myObj) {
myObj.testing();
}
and it should work.
Update of the question:
Edit: The reason I have left the parameter in myMethod as type Object, is because I would like to be able to pass in a variety of object types, each having a testing() method.
As Amanda S and several others have said, this is a perfect case for an interface. The way to do this is to create an interface which defines the testing() method and change myMethod to take objects implementing that interface.
An alternative solution (without interfaces) would be to reflectively discover if the object has a testing() method and call it, but this is not recommended and not needed for a such a simple case.
What you are talking about is duck typing. Java doesn't have duck typing.
Therefore you need to define an interface that all the classes with a testing() method implement.
e.g:
public interface Testable
{
public void testing()
}
class B implements Testable
{
public void testing() {
System.out.println ("TESTING!!!");
}
}
class A {
public static void myMethod(Testable myObj) {
myObj.testing();
}
}
Your issue is a classic argument in favor of an interface. You want as generic as possible, yet you want every object you pass to have a testing() method. I suggest something along the lines of the following:
public interface Testable
{
public void testing();
}
public class A
{
public static void myMethod(Testable myObj)
{
myObj.testing();
}
}
public class B implements Testable
{
public void testing()
{
System.out.println("This is class B");
}
}
public class C implements Testable
{
public void testing()
{
System.out.println("This is class C");
}
}
public class Test
{
public static void main (String[] args)
{
B myB = new B();
C myC = new C();
A.myMethod(myB); // "This is class B"
A.myMethod(myC); // "This is class C"
}
}
Because you're passing in an Object (b inherit from Object). Object doesn't have testing, b does.
You can either pass in b or cast the object to b before calling the method.
EDIT
To pass in a generic class that implements that method: you'll want to make an interface that has the method signature and pass in the interface type instead of Object. All objects that you pass in must implement the interface.
You can only access the members that are visible for the type of reference you have to the object.
In the case of myMethod(Object myObj) that means only the members defined in Object, so in class a the members of class b will not be visible.
If you changed the definition of a.myMethod to be public static void myMethod(b myObj) you would then be able to see the testing method on the instance of b while in myMethod.
update based on clarification:
In that case defining an interface for all of them to implement is likely what you want.
public interface Testable {
public void testing();
}
public class a {
public static void myMethod(Testable myObj) {
myObj.testing();
}
}
public class b implements Testable {
public void testing () {
System.out.println("TESTING!!!");
}
}
Why can’t java find my method?
Because of the way Java was designed.
Java is "statically typed" that means objects types are checked during compilation.
In Java you can invoke a method only if that method belongs to that type.
Since this verification is made during compilation and the Object type does not have the "testing()" method, the compilation fails ( even though if at runtime the objects do have that method". This is primarily for safety.
The workaround as described by others will require you to create a new type, where you can tell the compiler
"Hey, the instances of this type will respond the the testing method"
If you want to pass a variety of objects and keep it very generic, one way is having those objects to implement and interface.
public interface Testable {
public void testing();
}
class A implements Testable { // here this class commits to respond to "testing" message
public void testing() {
}
}
class B implements Testable { // B "is" testable
public void testing() {
System.out.println("Testing from b");
}
}
class C implements Testable { // C is... etc.
public void testing() {
//....
}
}
Later somewhere else
public void doTest( Testable object ) {
object.testing();
}
doTest( new A() );
doTest( new B() );
doTest( new C() );
The "OTHER" way to do this, in java is invoking the methods reflectively, but I'm not sure if that's what you need, for the code is much more abstract when you do it that way, but that's how automated testing frameworks (and a lot of other frameworks such as Hibernate) do actually work.
I hope this help you to clarify the reason.
If you REALLY, REALLY want to keep the parameter as abstract as possible, you should consider reflection API. That way, you can pass whatever object you want and dynamically execute the method you want. You can take a look at some examples.
It's not the only way, but it might be a valid alternative depending on your problem.
Keep in mind that reflection is way slower than calling your methods directly. You might consider using an interface as well, such as the one on Amanda's post.