is there any way to use static-method without class? - java

package java;
//----------------------------- add one more line in here
class Demo {
public static String prt(String name) {
return "my name:" + name;
}
}
public class Sample {
public static void main(String[] args) {
System.out.println(prt("hong"));
}
}
if there is any way to print
my name : hong
,please let me know.

You can do this by creating an instance of the Demo class with new Demo(), like this:
class Demo {
public static String prt(String name) {
return "my name:" + name;
}
}
class Sample {
public static void main(String[] args) {
System.out.println(new Demo().prt("hong"));
}
}

You should be able to reference it via the class name:
Demo.prt("Hong")
however, if you can't use class Demo, then I'm not exactly what real life situation this would be. Methods belong to classes, they do not exist on their own. They must be referenced by classes, or instances of the class. Unless you're providing more context on your question, the answer is No.
However, if you can reference it by object, you could do this:
Demo demo = new Demo();
System.out.println(demo.prt("hong"));

Related

How can I use non static variable(object ref) in static method without creating object inside that static method in java?is there any way to do it?

I'm new to Java. I get this error when running the code below
Cannot make a static reference to the non-static field universityObj
But not getting error while using
University universityObj = new University();
The code:
public class University {
String name;
int stuno;
String university_name = "Michigan University";
University universityObj;
public static void main(String[] args)
{
University universityObj = new University();
universityObj.name="Robert";
universityObj.stuno=12;
System.out.println(universityObj.name);
System.out.println(University.university_name);
display();
}
public void nonStaticDisplay()
{
System.out.println(name);
System.out.println(stuno);
}
public static void display()
{
universityObj = new University();
System.out.println(universityObj.name);
}
}
Let's go step by step.
The display() method should be non-static because it belongs to and should be used on the specific instance of the University class. Static methods can be used without creating an instance of some class. But in the case of the display() method, it wouldn't makes sense to do that because you need to display the university name, which firstly should be created and assigned.
It's not a good idea to create the object instance University universityObj inside the class in your case. Better to leave it only in the main method.
The university_name name is not static, so you can't access it without the class instance (object) like you're doing right now. University.university_name should be changed to universityObj.university_name.
These steps will bring us to a such piece of code:
public class University {
String name;
int stuno;
String university_name = "Michigan University";
public static void main(String[] args) {
University universityObj = new University();
universityObj.name = "Robert";
universityObj.stuno = 12;
System.out.println(universityObj.name);
System.out.println(universityObj.university_name);
universityObj.display();
}
public void display() {
System.out.println(name);
System.out.println(stuno);
}
}
Other things, which you should consider:
Read about encapsulation.
Use code formatting in your IDE. Example for IntelliJ IDEA.
Check the toString() method from the Object class. It's intended exactly for what you're trying to achieve with your display() method.
You might simply pass a reference to the instance you want to be displayed. Like,
public static void display(University universityObj)
{
System.out.println(universityObj.name);
}

Is it possible to avoid using "static" when call variable from another class?

Is it able to avoid using "static" when call variable from another class? thank you very much
Here is my code.
class Hello {
public static String say = "Hello World"; //I using static
public void born() {
System.out.println(say);
}
}
public class SayHello extends Hello {
public static void main(String[] args) {
Hello myHello = new Hello();
myHello.born();
System.out.println(say);
}
The Output:
Hello World
Hello World
If I use public String say = "Hello World";
it output Hello World null
AnyIdea to avoid using "static" when call variable from another class?
thank you very much
If you remove the static, it will not compile. Static fields can be marked private, if you want to hide them. So then they are reachable by all instances of the class Hello only. The proper way of modifying or getting would be:
class Main extends Hello {
public static void main(String[] args) throws Exception {
Hello myHello = new Hello();
myHello.born();
// System.out.println(say); //doesn't allow access
// System.out.println(Hello.say); //doesn't allow access
System.out.println(myHello.getSay());
}
}
class Hello {
private static String say = "Hello World"; //private
public void born() {
System.out.println(say);
}
public String getSay() {
return say;
}
}
A static variable is common to all the instances (or objects) of the class because it is a class level variable. In other words you can say that only a single copy of static variable is created and shared among all the instances of the class.
So if you don't want to use static, then you can't use it in the other instances of class.
Yes, if you don't declare it static you can reference it from an instance: myHello.say.
It is the same as for calling a function.
public class SayHello extends Hello {
public static void main(String[] args) {
Hello myHello = new Hello();
myHello.born();
System.out.println(myHello.say);
}
}
For a constant, ie. a String that never changes and is the same for all instances of the class, it makes sense to declare it static and use it as such.
If you don't mark the string as static you will get a compilation error because when you do System.out.println(say) in the main method you are using say in a static context (since the main method must be static).
If you remove System.out.println(say); and just leave myHello.born(); then there's no need for say to be static because you'll only be using it from non-static methods (i.e. the born() method). You can see it in this example where I commented that line and defined say as not being static.
Another option would be to make the println like this, since the variable is public: System.out.println(myHello.say);

Java: Trouble understanding how to call instance from other class

I've been flustered over trying to figure out how to call a method from an instance of a class from a different class. For example:
public class Test1
{
public static void makeSomeInst()
{
Test1 inst = new Test1();
inst.fireTest();
}
public void fireTest()
{
System.out.println("fireTest");
}
public Test1()
{
}
}
no problem with understanding the above, but what If I want to do something to inst from a class called Test2, how would I do that? The below example doesn't work:
public class Test2
{
public static void main(String[] args)
{
Test1.makeSomeInst();
inst.fireTest();
}
}
And just to be extra clear, I get that I can call static references without instantiating, but I just want to know, in this specific case
What is the syntax to reference the test1 object called inst from the Test2 class?
what If I want to do something to inst from a class called Test2, how would I do that?
First of all you have to teach the Test2 class what Test1 is.
public class Test2
{
public doSomething()
{
inst.fireTest();
}
public Test2(Test1 inst)
{
this.inst = inst;
}
private Test1 inst;
}
Then teach the inst2 object what inst is.
public class Test1
{
public static void main(String[] args)
{
Test1 inst = new Test1();
Test2 inst2 = new Test2(inst); // <- new code
inst2.doSomething(); // <- new code
}
public void fireTest()
{
System.out.println("fireTest");
}
public Test1()
{
}
}
You only need one main to start the show. Flow of control can still pass through other objects. But at this point I wouldn't call these independent tests. I only used that name to match your code.
What you're looking at is something called reference passing. The fancy term for it is Pure Dependency Injection*. The basic pattern is to build an object graph in main. Once that's built call one method on one object to start the whole thing ticking.
In main you build every object that will live as long as your program does. What you wont find built here are objects that are born later, such as timestamps. A good rule of thumb is to build each of these long lived objects before doing any real work. Since they know about each other they can pass flow of control back and forth between them. There's a lot of power there and if not used well it can get confusing. Look into Architectural Patterns to help keep that simple.
The principle followed here is to separate use from construction. Following that allows you to easily change your mind about what talks to what in one place. It's nice when a design change doesn't force you to rewrite everything.
You have to save your instance somewhere.
If Test1 should be a singleton, you can do:
public class Test1
{
private static Test1 instance;
public static Test1 getInstance()
{
return instance == null ? instance = new Test1() : instance;
}
public static void main(String[] args)
{
Test1 inst = getInstance();
inst.fireTest();
}
public void fireTest()
{
System.out.println("fireTest");
}
}
and in Test2:
public class Test2
{
public static void main(String[] args)
{
Test1.getInstance().fireTest();
}
}
//Edit
As I just learned from #Thomas S. comment, singletons are not a good solution.
See #candied_orange's answer for a better implementation.

pass string to main method in another class

I'm creating a project that need to pass string from first program to second program but i need to pass string in main method of first class. I've googled but i cannot find what i need, mostly people use setter and getter to pass string between class but i cannot do that in main method.
How to pass string in main method of another class?
what i need is shown here:
public class FirstProgram{
public void first(){
String a = "hello";
}
}
public class SecondProgram{
public static void main(String[] args){
//i need to pass string here
}
}
Its not a good approach to take, but technically you can call the main method of the Second program and pass whatever argument you like
public class FirstProgram{
public void first(){
String a = "hello";
SecondProgram.main(new String []{a});
}
}
You can do this:
First.java:
public class First {
public static void main(String[] args) {
Second.main(args);
}
}
Second.java:
import java.util.Arrays;
public class Second {
public static void main(String[] args) {
Arrays.stream(args).forEach(System.out::println);
}
}
If you execute java First foo bar baz bat on the command line, you'll see that Second prints out "foo bar baz bat" in the console.
I don't recommend it.
You have to start your app by calling main in some program. Your First can invoke main in Second as shown, but it's First that starts the process.
Pretty confusing question.
But you can do smth like that:
public class FirstProgram{
public String first(){
String a = "hello";
return a;
}
}
public class SecondProgram{
public static void main(String[] args){
FirstProgram firstProgram = new FirstProgram();
String result = firstProgram.first();
}
}

I want dynamic way to get the package name from any class in java

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();

Categories

Resources