methods of objects within main - java

Is it possible to instantiate an object in a method within a class and then use one of the methods of the instantiated objects within main? Can I fix the following code?
public class Test {
public void Testmethod() {
someclass a = new someclass();
}
public static void main(String[] args) {
a.methodfromsomeclass();
}
}

There are three problems you need to fix:
1) You've declared a to be a local variable inside Testmethod. This means it can be accessed only inside Testmethod. If you want a variable that will live even after Testmethod is done executing, you should make it an instance variable of Test. That means that an instance of Test will contain the variable, and instance methods of Test, other than Testmethod will be able to access it.
Declaring an instance variable looks something like this:
public class Test {
private someclass a; // please choose a better variable name
//...... other code ..........//
}
2) main won't be able to access the instance variable, because main is static. You can't make main non-static, either; Java requires it to be static. What you should do is write an instance method (called doMainStuff, for example, or some better name), and have your main create a new Test object, something like:
public void doMainStuff() {
// something that calls Testmethod
a.methodfromsomeclass(); // use a better name than "a"
// other code
}
public static void main(String[] args) {
new Test().doMainStuff();
}
3) The way you've written it so far, a new someclass would never be constructed, since you never call Testmethod. You'll need to make sure you call Testmethod before you try to use a. (It doesn't automatically get called just because it appears in the code. You have to write code that calls it.)
Also, please obey proper naming conventions: classes begin with an upper-case letter (SomeClass), methods begin with a lower-case letter (testMethod), and if a name has multiple words, the second and later words begin with upper-case letters.

Related

How to pass class method as a parameter before the instance is declared?

What I want to do is like this. My question is how can I call tm.test in inner.
// TestMain is a class implemented handler
public void outer() {
inner(TestMain::test); // call inner
}
public void inner(handler h) {
TestMain tm = new TestMain();
//invoke tm.h(), i.e. invoke tm.test() in this example
}
public interface handler<M> {
void entitySelector();
}
I know how to call tm.test in inner if tm is declared in method outer, i.e. pass the function as tm::test
But I have to declare the instance every time I call inner.
Simply spoken: you can't. And even it would be possible, you shouldn't do something like that.
There is the "principle of least surprise": you don't that people reading your code tell you "wtf?!" because your code surprises them.
In other words: you should step back and see if your design really makes sense this way. Can't you use a fixed tm instance for example; one that sits as field on your class; instead of being a local variable in your method?

Ways of calling non static method from main in Java

We all know that we cannot call a non-static method from Java's static main method directly. I've written 2 ways to call non-static method from main (shown below).
What I wanted to ask is: Is there any significance difference between using code 1 and code 2 to overcome the limitation?
Code 1
public class Demo
{
public static void main(String[] args)
{
Demo demo = new Demo();
demo.printText();
}
public void printText()
{
System.out.println("Method successfully called.");
}
}
Code 2
public class Demo
{
public static void main(String[] args)
{
new Demo().printText();
}
public void printText()
{
System.out.println("Method successfully called.");
}
}
NOTE: In school, our professor told us "In Java, staticmethods of a class can be invoked through the name of the class in which they are defined, without having to instantiate an object of the class first."
But in code 2 no object was instantiated, yet I was able to call the non static-method?
There are 2 main things to be considered while using the first one over the second..
you will still have a reference to the Demo object, so you can call demo.someOtheMethod().
Your demo object will not be ready for Garbage collection as soon as printext() returns. i.e, it will not be ready until you actually exit main(). In the second case, it will be ready as soon as printext() returns..
The only difference is that you can reuse the value in the object demo later. However, you should not create an instance just to call such a method. The correct way to do this is to make the method static.
There is no any difference of executing code or the creating the object.
But in the second method, you don't have a reference to the object you created.(in first method, demo is the reference for the Demoobject) So you can't do any other thing with this object further, as there is no way of referencing it.
as example:
Suppose you had another method inside class Demo called foo1()
in first example you can run both method using a single object.
Demo demo = new Demo();
demo.printText();
demo.foo1();
but in the second method, You have to do it with 2 objects seperately.
new Demo().printText();
new Demo().foo1();
In Code1, you are creating an object using the class name as a reference variable, and calling that function and this would work very finely.
in code2, you are creating an anonymous object, which is basically used whenever we want to use the object only once in the lifecycle of the class.
In both code, the program will work finely.

regarding static method in java

When studying the java programming language, I meet the following statement
I am confusing about the statement marked with yellow. Especially, what does instance method mean here? If there is an example to explain this point, then it would be much appreciated.
If I have a method:
public static void print(String line) {
System.out.println(line);
}
... and then remove the static keyword ...
public void print(String line) {
System.out.println(line);
}
... it is now an instance method, can no longer be invoked from the class, and must instead be invoked from an instance (hence the name).
e.g.,
MyClass.print(line);
vs.
new MyClass().print(line);
That's really it.
You can call static methods without needing to intantiate an object:
TestObject.staticMethodCall();
For non-static methods you need to create an instance to call a method on:
new TestObject().nonStaticMethodCall();
Consider following sequence.
Define Class X with static void foo() a static method
Define Class Y which calls X.foo() in its main method
Compile the two classes and (somehow) run it
Change X.foo() to be a instance method by removing the static qualifier
Compile only X, not Y
Run the Y class again and observe the error.
On the other hand, if you had changed the body of X.foo in certain ways without changing its static-ness then there would have been no error. For more, look up "binary compatibility"
First of all, you should understand the difference between the class method and the instance method. An example is shown below.
public Class Example{
public static void main(String[] args) {
Example.method1();//or you can use method1() directly here
Example A = new Example();
A.method2();
}
public static void method1(){
}
public void method2(){
}
}
method1 is the class method which you can take it as the method of the class. You can invoke it without initiating a object by new method. So you can invoke it in such way: Example.method1()
method2 is the instance method which requires you to invoke it by initiating the instance of an object, i.e. Example A = new Example(); A.method2();
Additional:
The error is due to the removal of the static modifier of an class method like method1. Then method1 becomes an instance method like method2 which you have to initiate an instance to call.

how to operate static?

Whenever we use static, we need not create a reference variable of a class. We can directly access class with the help of <class_name>
But when we write the following code:
class Abc
{
static void show()
{
System.out.println("Hey I am static");
}
}
class Test
{
public static void main(String args[])
{
Abc.show(); //1
new Abc().show(); //2
}
}
How does both the lines 1 & 2 work. what is the significance of
new Abc().show();
Using an instance (although it works) is the wrong way of invoking a static method (or access static fields) because static denotes its a member of the class/type and not the instance.
The compiler would therefore replace the instance with the Class type (due to static binding). In other words, at runtime, ABC.show() gets executed instead of new ABC().show().
However, your source code would still look confusing. Hence, it's considered a bad practice and would even result in warnings from IDEs like Eclipse.
Since your ABC class did'nt override the default constructor.
It's equivalent to :
class Abc{
public Abc(){super();}
static void show(){
System.out.println("Hey I am static");
}
}
Hence by doing new Abc().show(); you're just creating a new Abc object of your class and call the static method of the ABC class throught this object (it will show a warning because this is not the proper way to call static method).`
You CAN use static methods from an instance, as in new Abc().show(), but it's potentially confusing and not recommended.
Stick to className.staticMethod() for static methods and classInstance.instanceMethod() otherwise.
It simple means that you are creating object to ABC and than trying to accessing this variable through object.
However, at the time of compilation,
new Abc().show();
is converted to Abc.show().
Static keyword suggests only one copy per class now you have created method static and you are accessing using Classname.methodname() that is appropriate way because when class is loaded into JVM its instance will be created so no need to exlicitly create new Object of the class. hope it make sense.

Can't access public non-static class attribute from secondary class

I have the following two classes:
public class Class1
{
public Class1 randomvariable; // Variable declared
public static void main(String[] args)
{
randomvariable = new Class1(); // Variable initialized
}
}
public class Class2
{
public static void ranMethod()
{
randomvariable.getSomething(); // I can't access the member "randomvariable" here even though it's public and it's in the same project?
}
}
I am very certain that it's a very fundamental thing I'm missing here, but what am I actually missing? The Class1 member "randomvariable" is public and so is the class and both classes are in the same project.
What do I have to do to fix this problem?
There are two problems:
Firstly, you're trying to assign a value to randomvariable from main, without there being an instance of Class1. This would be okay in an instance method, as randomvariable would be implicitly this.randomvariable - but this is a static method.
Secondly, you're trying to read the value from Class2.ranMethod, again without there being an instance of Class1 involved.
It's important that you understand what an instance variable is. It's a value associated with a particular instance of a class. So if you had a class called Person, you might have a variable called name. Now in Class2.ranMethod, you'd effectively be writing:
name.getSomething();
That makes no sense - firstly there's nothing associating this code with Person at all, and secondly it doesn't say which person is involved.
Likewise within the main method - there's no instance, so you haven't got the context.
Here's an alternative program which does work, so you can see the difference:
public class Person {
// In real code you should almost *never* have public variables
// like this. It would normally be private, and you'd expose
// a public getName() method. It might be final, too, with the value
// assigned in the constructor.
public String name;
public static void main(String[] args) {
Person x = new Person();
x.name = "Fred";
PersonPresenter.displayPerson(x);
}
}
class PersonPresenter {
// In a real system this would probably be an instance method
public static void displayPerson(Person person) {
System.out.println("I present to you: " + person.name);
}
}
As you can tell by the comments, this still isn't ideal code - but I wanted to stay fairly close to your original code.
However, this now works: main is trying to set the value of an instance variable for a particular instance, and likewise presentPerson is given a reference to an instance as a parameter, so it can find out the value of the name variable for that instance.
When you try to access randomvariable you have to specify where it lives. Since its a non-static class field, you need an instance of Class1 in order to have a randomvariable. For instance:
Class1 randomclass;
randomclass.randomvariable.getSomething();
If it were a static field instead, meaning that only one exists per class instead of one per instance, you could access it with the class name:
Class1.randomvariable.getSomething();

Categories