Calling a static method of an abstract class in another class - java

I have a class Employee
import javax.swing.*;
public abstract class Employee {
public static void searchEmp(int id) {
JOptionPane.showMessageDialog(null, "done");
}
}
Now I have another class test:
public class `test` {
public static void main(String args[]) {
searchEmp(2);// here my programme give error
}
}
I want to call the searchEmp() which is part of Employee from a class test but it gives an error. Please suggest any solution without inheritance.

You have to call Employee.searchEmp().
The static method searchEmp() is still a member of the class Employee and you must make a static call via its class.
Also the class Employee must be visible to the class test, otherwise you have to import it. I assume the two classes reside in the same package so this will not be a problem in your case.

Static methods and properties are bound to class. So you need to use ClassName.methodName or ClassName.propertyName.
Employee.searchEmp();

Your Test class doesnt have a static searchEmp(int) method, thus the error:
searchEmp(2);// here my programme give error
should be
Employee.searchEmp(2);
static methods are called using ClassName.staticMethod()

Related

Can we create an object of the class in which main function is defined in Java?

Is it possible to create object of class in which main method resides.I have been searching for this answer but I have been told that it depends on compiler some compiler will allow while others will not.Is that true?
Yes? The main method is just an entry point. The class is like any other, except it has an additional public static method. The main method is static and therefore not part of the instance of the object, but you shouldn't be using the main method anyway except for starting the program.
public class Scratchpad {
public static void main(String[] args) {
Scratchpad scratchpad = new Scratchpad();
scratchpad.someMethod();
}
public Scratchpad() {
}
private void someMethod() {
System.out.println("Non-static method prints");
}
}
Yes, you can create object for the class which has main method. There is no difference in this class and a class which don't have main method with respect to creating objects and using.

Can't call a static method from another class to main class

I created a static method which returns a static int in class NewTriangle. But when I try to call it from the main it won't print. It asks to create a method with the same name inside the main.
public class NewTriangle{
public static in numberOfTriangles;
public static int getnumberOfTriangles(){
return numberOfTriangles;
}
}
The code works up until this point. But When I call getnumberOfTriangles() from the main I get an error.
public static void main(String args[]){
System.out.println(getnumberOfTriangles());
}
If your main method is in a different class, then you need to specify the classname while calling the static method, i.e., NewTriangle.getnumberOfTriangles()
Assuming the typos in your code are copy and paste errors, you need to either
Use the class name before the method name, you may need to add the class to your import statements (you need to if it is in a different package)
System.out.println(NewTriangle.getnumberOfTriangles());
Add a static import of the getnumberOfTriangles method to your main class
import static NewTriangle.getnumberOfTriangles;
However, note the caution given in the link:
So when should you use static import? Very sparingly!
You have to write the name of the class before :
NewTriangle.getnumberOfTriangles()
You can do something like this:
Example using :
I have created a package name stackoverflow
Two class callerClass and NewTriangle in package stackoverflow.
Make an import of class NewTriangle in callerClass.
using the Static function by NewTriangle.getnumberOfTriangles()
NewTriangle.getnumberOfTriangles() // className.StaticfunctionName()
Working Code:
Class 1 :
package stackoverflow;
public class NewTriangle {
public static int numberOfTriangles;
public static int getnumberOfTriangles() {
return numberOfTriangles;
}
}
Class 2 :
package stackoverflow;
import stackoverflow.NewTriangle;
public class callerClass {
public static void main(String args[]) {
System.out.println(NewTriangle.getnumberOfTriangles());
}
}
Java static method :
If you apply static keyword with any method, it is known as static method.
A static method belongs to the class rather than object of a class.
A static method can be invoked without the need for creating an instance of a class.
static method can access static data member and can change the value of it.
I hope I was helpful :)

Calling main method class from another java class

I have two java classes.One in which my GUI is written and the other class in which i have implemented an interface(call it class 2).My project starts from the main method of GUI.I want to send a string to my GUI class from the class 2 for displaying it in the Text area but nothing is happening.
As my main gui class is
public class GraphicalInterface extends javax.swing.JFrame{
//I have created a function over here for displaying string in text area
public void show1(String name)
{
jTextArea1.setText(name);
}
//buttons code
public static void main(String args[]) {
//code
}
}
I have created an object of this class in my class 2 like below
GraphicalInterface b=new GraphicalInterface();
b.show1("pear");// it does not allow me to write this statement
Please help me out that how can i call main method class from another java class.Thanks.
You may be trying to call this code outside of a constructor or method (or initializer block) and in Java, this can't be done. Instead call this code inside of a method or constructor.
I guess that you have a design problem in your project. Let me expain. You say you have a GUI class "GraphicalInterface" which holds the main method which is the starting point of an application in Java. You say you need to call the main method of this class in another class,
"your class 2". If so why isn't the place belonging to the "main method" of your application in which you try to call this GUI's main method. Call GUI's main method x(), let the place that you call x() belong to the main method.
If you need to operate on the GUI's fields in another classes and also keep the main method still there, then I suggest you to apply Singleton Pattern to your GUI class. In that way you
will be able to refer the only instance of your public singleton class everywhere in your application.
public class GraphicalInterface extends javax.swing.JFrame
{
public String textAreaContent;
public getX()( return textAreaContent;)
public setX(String s)( this.textAreaContent = s;)
public void show1()
{
jTextArea1.setText(this.getTextAreaContent());
}
public static void main(String args[])
{
//code
}
}
From your other class:
GraphicalInterface b=new GraphicalInterface();
b.setX("text area content");
b.show1();
No, the best solution is not to do this, and if you feel you must, it is likely because your design is somehow broken. Instead write your code so that your classes are true OOPs classes that interact in an intelligent way (low coupling, high cohesion), and to only need one main method.
Also, you state:
GraphicalInterface b=new GraphicalInterface();
b.show1("pear");// it does not allow me to write this statement
What do you mean by "it does not allow me to write this statement"? Does the Java compiler give a compilation error? Does the JVM throw an exception? Does the JVM reach out of your monitor and slap you in the face? Please let us know all the details necessary to be able to help you.
You need to create a method in class2 and call it from your main method.
Sample code class1
public class Test1 {
public void show(String ab){
System.out.println(ab);
}
public static void main(String[] args) {
Test2.Test2();
}
}
Above code i create a class Test1.java like your class1 and create a method with one parameter and call it from class2 method.
Sample code class2
public class Test2 {
static void Test2(){
new Test1().show("Pass String to class1 show method");
}
}
here you can pass your string value.

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.

java basics static method

can a static method be invoked before even a single instances of the class is constructed?
absolutely, this is the purpose of static methods:
class ClassName {
public static void staticMethod() {
}
}
In order to invoke a static method you must import the class:
import ClassName;
// ...
ClassName.staticMethod();
or using static imports (Java 5 or above):
import static ClassName.staticMethod;
// ...
staticMethod();
As others have already suggested, it is definitely possible to call a static method on a class without (previously) creating an instance--this is how Singletons work. For example:
import java.util.Calendar;
public class MyClass
{
// the static method Calendar.getInstance() is used to create
// [Calendar]s--note that [Calendar]'s constructor is private
private Calendar now = Calendar.getInstance();
}
If you mean, "is it possible to automatically call a specific static method before the first object is initialized?", see below:
public class MyClass
{
// the static block is garanteed to be executed before the
// first [MyClass] object is created.
static {
MyClass.init();
}
private static void init() {
// do something ...
}
}
Yes, that is exactly what static methods are for.
ClassName.staticMethodName();
Yes, because static methods cannot access instance variables, so all the JVM has to do is run the code.
Static methods are meant to be called without instantiating the class.
Yes, you can access it by writing ClassName.methodName before creating any instance.
Not only can you do that, but you should do it.
In fact, there are a lot of "utility classes", like Math, Collections, Arrays, and System, which are classes that cannot be instantiated, but whose whole purpose is to provide static methods for people to use.
Yes, that's definitely possible. For example, consider the following example...
class test {
public static void main(String arg[]) {
System.out.println("hello");
}
}
...if then we run it, it does execute, we never created a instance of the class test. In short, the statement public static void main(String arg[]) means execute the main method without instantiating the class test.

Categories