Method main is never used locally! Why? - java

I am taking a class in java and have some problems with this code: It says that classOne and the main String are never used locally. Why?
public class classA {
private static class classOne{
protected static int a;
protected static String b;
public Haustier (int x, String y){
a= x; b = y;
}
void print (int a, String b){
System.out.println("this is a result "+a+" . This is also a "+b+" result.");
}
public static void main(String[] args){
classOne H1 = new classOne(4, "Fluffy");
classOne H2 = new classOne(3, "Lessi");
H1.print(a, b);
H2.print(a, b);
}
}
}
The question in a nutshell: Implement a class, a constuructor, a method and print the result via System.out.println.
(of cause there are more details, but this would be the short version.)
Thank you for your help.

I am having to make some guesses here: you wrote this code in an attempt to solve the problem of which you give a brief description?
I am going to guess that you did not know that, although it is legal to put one class inside another class, that it is somewhat advanced and not something you are liable to need for an introductory assignment.
Your ClassA is sufficient to solve the problem, there is no need to declare another class at all. Dispense with ClassOne altogether. You will need a main method in ClassA; that is where execution will start once you start the resulting java program. Separately, you can write a constructor for ClassA, and the main method of that class can invoke it to create an instance of the ClassA class. You could also implement a method for ClassA besides main; you can just declare it public void printValue() or something like that, and then call it using the variable holding the ClassA instance that you created. Those two lines would look something like this:
ClassA classAInstance = new ClassA(); // here you are using your constructor
classAInstance.printValue(); // here you are calling your method.
See if you can put the rest of it together yourself. Good luck

Related

what is the best way to get other class of object reference??

Sorry, i can't give better title.I have two class A and B.A class is singleton class.it always gives same object to whoever want it.Here B class always want that A object refenence. check follow code
class B
{
private A a;
B(){
this.a=A.getAObject();
}
public void process(String[] args)
{
a.sendData();//line 1
(or)
A.getAObject().sendData();//line 2
}
}
which is best way as mentioned above line 1 or line 2 as performance wise like that??
You can reference of one class to another class by making reference of the other class
In your code you do something like this :
class B {
private A a;
B(A a){
this.a=a; //refernce of a
}
public void display(){
a.getA(); //display method of a
}
}
class A{
public void getA(){
....
}
}
In many cases the differences will be insignificant.
But there would be scenarios like where you have to create a lot of instances of B. So in those scenarios there would be a performance impact since introducing a filed to that class means taking more memory when creating a instance.
If it is not a scenario like that, I think its better to assign it to a variable, since it will improve the readability of the code if you use that instance often in the class.

Why make an object for Main class, for the methods to work?

I was facing an error before, but when I made an object in this class the and called for the method, it worked flawlessly. Any explanation? Do I always have to make an object to call for methods outside of the main method (but in the same class)?
here:
public class A{
public static void main(String[] args){
A myObj= new A();
System.out.println(myObj.lets(2));
}
public int lets(int x){
return x;
}
}
You need to understand static. It associates a method or field to the class itself (instead of a particular instance of a class). When the program starts executing the JVM doesn't instantiate an instance of A before calling main (because main is static and because there are no particular instances of A to use); this makes it a global and an entry point. To invoke lets you would need an A (as you found), or to make it static (and you could also limit its' visibility) in turn
private static int lets(int x) {
return x;
}
And then
System.out.println(lets(2));
is sufficient. We could also make it generic like
private static <T> T lets(T x) {
return x;
}
and then invoke it with any type (although the type must still override toString() for the result to be particularly useful when used with System.out.println).
There are a importance concept to consider an is static concept. In your example you have to create an instance of your class because the main method is static and it only "operate" with other statics methods or variable. Remember that when you instantiate a class you are creating a copy of that class an storing that copy in the instance variable, so as the copy (That was create inside of a static method in your case) is also static so it can access the method which is not static in that context.
In order to not create an instance and access to your method you need to make your lets method static(due to the explanation abode)
public static int lets(int x){
return x;
}
And in your main you don't need to instantiate the class to access to this method.
public static void main(String[] args){
System.out.println(lets(2));
}
Check this guide about static in java: https://www.baeldung.com/java-static
Hope this help!

How can i access one class variable into other

There are to separate classes class One and class Two. Both of classes are in same package. I want to access one class data into other class how can i access variable data. My program is very lengthy ,I just want the logic of this.Thanking you in advance.
Class A.java
public class A
{
public static void main(String ar[])
{
int a=100;
}
}
Class B.java
public class B extends A
{
public static void main(String m[])
{
A obj=new A();
System.out.println("Variable of class A is :"+ obj.a);
}
}
I have done this thing to get access like i declared variable a as Static so that i can directly get access but it's not working. and when i am compiling B.java It giving me error
cannot find symbol at := System.out.println("Variable of class A is :"+ obj.a);
And
Illegal start of expression (when i am delaring variable a as public)
:-(error)public int a=100; [in class A].
Why are you using the static main method? Besides that the field a is local and not accessible outside the scope. Use this instead.
public class A
{
public int a;
public A()
{
a=100;
}
}
You don't have two true object-oriented classes above, but rather little more than two receptacles for static main methods. To combine code from two classes well, you will want to scrap that code and make OOP-compliant classes, complete with instance fields and methods. For more on this, check out the OOP section of the Java tutorials: link to OOP tutorial.
First, get rid of main() in A. You only want one main() in your application, and it's in B (since the one in A doesn't actually do anything):
public class A {
}
Now, you want A to have a class-level int value:
public class A {
private int a;
}
And you want it to have a default value of 100, yes? A constructor is a good place to do that:
public class A {
private int a;
public A() {
this.a = 100;
}
}
Now any time you do this:
A obj = new A();
you will have an object with a value. In order to access that value from outside that object, you need a "getter":
public class A {
private int a;
public A() {
this.a = 100;
}
public int get_a() {
return this.a;
}
}
Now in B (or anywhere, really), you can create an instance of A and access that value by using the "getter":
A obj=new A();
System.out.println("Variable of class A is :"+ obj.get_a());
Semantically, don't think of it as "accessing a variable from another class". Instead, think of what your objects are and what they represent. If it were a physical, real-world object which internally contained some kind of value.
When you create an instance of that object, the instance would internally have that value somewhere. From the outside of that object, it doesn't really matter how that value is internally maintained. There just needs to be some kind of interface to see the value. Which is what the "getter" method does.
One-liner answer: To access a variable outside a class, make it class-level. You have written a method-level variable that's accessible only inside that scope (method).
To elaborate:
There are to separate classes class One and class Two. Both of classes are in same package. I want to access one class data into other class how can i access variable data.
So basically you know that to by extending, you should be able to access parent class data into your subclass. For that, simply make the data in your parent class as class level.
class A {
int var = 10; //class level, but non-static, so to access you need A object
void method() {
int var = 20; //this is method local and can not be accessed outside
}
}
public class B extends A {
public static void main(String[] args) {
A aObj = new A();
System.out.println(aObj.var);
}
}
Illegal start of expression (when i am delaring variable a as public)
Its illegal. Because access modifiers like public, private etc. are applicable to class-level stuff like the first var or the main method in class B you see.
Said that:
You need to immediately go here: https://docs.oracle.com/javase/tutorial/
rather than just trying to run some classes when you lack language basics.

Is it possible for a static method to refer to "this" in Java?

I am new to Java. I know static is class level and this is object level but please let me know if a static method can refer to the this pointer in java?
No it does not make sense to refer this in static methods/blocks. Static methods can be called without creating an instance hence this cannot be used to refer instance fields.
If you try to put this in a static method, compiler will throw an error saying
cannot use this in static context
No, this cannot be accessed in a static context. June Ahsan said everything that you probably need to know but I would like to add a little background.
The only difference between an object method and a static method on byte code level is an extra first parameter for object methods. This parameter can be accessed through this.
Since this parameter is missing for static methods, there is no this.
Example:
class MyClass {
private int b;
public void myMethod(int a){
System.out.println(this.b + a);
}
public static void myStaticMethod(int a){
System.out.println(a*a); // no access to b
}
}
on byte code level becomes (roughly speaking, because byte code does not look like this)
class MyClass {
int b;
}
void myMethod(MyClass this, int a){
System.out.println(this.b + a);
}
static void myStaticMethod(int a){
System.out.println(a*a); // no access to b
}
No but you can create a static object of you class in your class like this
private static ClassName instance; and then you can set it with instance = this; in the constructor. this will then be available for you to use in a static method.

Why can't you instantiate the same object of that class inside constructor?

public class Run{
public static void main(String... args){
A a1 = new A();
}
}
class A{
public A(){
A a = new A();
}
//here as well A a = new A();
}
Why does this give a java.lang.StackOverflowError? Is there a recursive call happening here? How does it happen?
You're calling the constructor inside the constructor--that's what new does, constructs a new object.
Is there a recursive call happening here?
Yup
How it happens?
When you new A(), it calls the constructor for A, which does a new A() which calls the constructor, which does a new A() ... and so on. That is recursion.
You can call, but it would be a recursive calling which will run infinitely. That's why you got the StackOverflowError.
The following will work perfectly:
public class Run{
static int x = 1;
public static void main(String... args){
A a1 = new A();
}
}
class A{
public A(){
if(x==1){
A a = new A();
x++;
}
}
}
The issue is that when you call the constructor, you create a new object (which means that you call the constructor again, so you create another object, so you call the constructor again...)
It is infinite recursion at its best, it is not related to it being a constructor (in fact you can create new objects from the constructor).
Basically none of your constructors will ever exit - each will get as far as trying to instantiate another object of type A recursively.
You need to change your constructor to actually create an A object. Suppose A holds an integer value and nothing more. In this case, your constructor should look like this:
class A{
int number;
public A(){
number = 0;
}
}
What you're doing in your code is actually creating a new object instance inside of your own constructor.
So, when you call new A(), you're calling the constructor, which then calls new A() inside of its body. It ends up calling itself infinitely, which is why your stack is overflowing.
I would think that there's a recursive call there. In order to create an A, you have to create another A inside of it. But to create that A inside of it, you have to create a third A inside of that A. And so on. If you use two different constructors or arguments or something though, you should be able to work around this:
class A {
public A(boolean spawn){
if (spawn) {
A a = new A(false);
}
}
}

Categories