What is the purpose of creating static object in Java? - java

class Demo {
void show() {
System.out.println("i am in show method of super class");
}
}
class Flavor1Demo {
// An anonymous class with Demo as base class
static Demo d = new Demo() {
void show() {
super.show();
System.out.println("i am in Flavor1Demo class");
}
};
public static void main(String[] args){
d.show();
}
}
In the above code, I do not understand the use of creating object d of Demo class with static keyword preceding it. If I eliminate the static keyword, it shows an error. Actually, I was going through anonymous inner class concept and got stuck here. Need help.... Can anyone please explain it?

The static keyword in Java means that the variable or function is shared between all instances of that class, not the actual objects themselves.
In your case, you try to access a resource in a static method,
public static void main(String[] args)
Thus anything we access here without creating an instance of the class Flavor1Demo has to be a static resource.
If you want to remove the static keyword from Demo class, your code should look like:
class Flavor1Demo {
// An anonymous class with Demo as base class
Demo d = new Demo() {
void show() {
super.show();
System.out.println("i am in Flavor1Demo class");
}
};
public static void main(String[] args) {
Flavor1Demo flavor1Demo = new Flavor1Demo();
flavor1Demo.d.show();
}
}
Here you see, we have created an instance of Flavor1Demo and then get the non-static resource d
The above code wont complain of compilation errors.
Hope it helps!

You get an error by removing static keyword from static Demo d = new Demo() because you are using that object d of class Demo in main method which is static. When you remove static keyword from static Demo d = new Demo(), you are making object d of your Demo class non-static and non-staticobject cannot be referenced from a static context.
If you remove d.show(); from main method and also remove static keyword from static Demo d = new Demo(), you won't get the error.
Now if you want to call the show method of Demo class, you would have to create an object of your Demo class inside main method.
public static void main(String[] args){
Demo d = new Demo();
d.show();
}

Thats because you try to use d that belongs to object in static method.
You would then have to create that object in main method.
static belongs to class, not object itself.
I want to know the difference between static method and non-static method

That depends on the context you are in.
The main(String[]) methods is a static methods.
To stay simple, that means it doesn't exist in an instance of Flavor1Demo, there is no this here. If you set d as non-static, it will only exist in an instance of Flavor1Demo so it can't be access from the main unless you build a instance first (new Flavor1Demo().d.show();
But a static variable will be link to the class an not an instance, Meaning you can access it from a static context. In you case, the main method.

In order to access methods or variables in main class without creating object in it,here we are defining anonymous inner class where we create object of static type so that its directly accessed from main class without creating the object.

There is no such thing as a static object in Java. The variable that points to the object can be static, but the idea of an object being static has no meaning.
The purpose of a static variable or any other static type member is to attach the member to the type itself rather than to an instance of the type.

Related

java- "new" operator in static method

I know this is reference variable which holds the reference for object and static method loads when the class is first accessed by class loader, either to create an instance, or to access a static method or field.
Why its not allowed for this but for instance itself? For e.g.
Class A{
public static void main(String... args){
this.method(); //not allowed
new A().method(); //allowed, how?
}
void method(){
System.out.println("Class A");
}
}
this.method(); //not allowed
You have no instance this in static context so you can't invoke method.
new A().method(); //allowed, how?
You have instance created by new operator so that you can invoke a method.
To invoke a method without having a real instance you have to declare it as static. i.e.:
static void method(){
System.out.println(“Class A”);
}
this will work when calling just method() and via instance:
public class A {
public static void main(String[] argv) {
method(); //works because method is static
new A().method(); //still ok, we can call static method using an instance
this.method(); //not allowed, there is no 'this' in static context
}
static void method(){
System.out.println("Class A");
}
}
static variables and instance variables follow the initialization order you mention when they are initialized in their declarations. Also static initializer blocks follow that order.
Methods (including constructors) on the other hand need no initialization at runtime. They are fully defined at compile-time and therefore exist and can be called as soon as the class is loaded, also before the initialization is complete. Therefore there is no problem in your main method instantiating the class (calling the default constructor) and calling a method that is declared later, as method is declared below main.
In addition, the main method is also only executed after any static initialization is complete.

Why can I use external non static classes and methods inside main, and can't with classes and methods defined inside the class?

I naturally can have classes inside any class, so in my main method. I also can access to its methods and its attributes.
But this code isn't working. I know main to be static, so is it something like:
The main method runs and is it the one constructing any class, even the one who contains it.
Then, main should start, construct the class who contains it, and then any class or method inside.
package holamundo;
public class HolaMundo {
public class AnotherClass {
// Class body
}
public void method () {
// Code
}
public static void main(String[] args) {
AnotherClass a = new AnotherClass();
method();
}
So doing:
package holamundo;
public class HolaMundo {
public static class AnotherClass {
// Class body
}
public static void method () {
// Code
}
public static void main(String[] args) {
AnotherClass a = new AnotherClass();
method();
}
We could say main is running first, among the AnotherClass and method definitions?
I tried writing this up with my own words, but the SCJP 6 book does it way better, so here it goes:
A static nested class is simply a class that's a static member of the
enclosing class
Perhaps to better understand, here's some code:
public class HolaMundo {
public static class AnotherClass {
public void hello(){
System.out.println("Hello");
}
public static void hola(){
System.out.println("Hola");
}
}
public static void main(String[] args) {
HolaMundo.AnotherClass.hola();
HolaMundo.AnotherClass holaAnother = new HolaMundo.AnotherClass();
holaAnother.hello();
}
}
Note that the above code in the main() method will continue to work if you remove the occurrences of HolaMundo..
If you're confused, here's more from the book:
The class itself isn't really "static"; there's no such thing as a
static class. The static modifier in this case says that the nested
class is a static member of the outer class. That means it can be
accessed, as with other static members, without having an instance of
the outer class.
A static method (like main()), doesn't belong (and also cannot access) to any particular instance of any class.
This means that a static method can create new instances of any class it has access to, even if it happens to be an instance of the class that declared said method in the first place.
Now, since in this case, main(), AnotherClass and method() are all static members of HolaMundo, then yes, this means that they all "run together".
More specifically, they are loaded when the class is first loaded by the JVM (aka at Class Loading time).
In Java, non-static nested classes have an implicit reference to an instance of the container class and so cannot be utilized in static contexts (like the main method) since there is no instance to reference.

Can non-static methods modify static variables

I am wondering how a non static method can modify a static variable. I know that static methods can only access other static methods and static variables. However, is the other side true? Can non-static methods access only non-static variables? For example:
public class SampleClass {
private static int currentCount = 0;
public SampleClass() {
currentCount++;
}
public void increaseCount() {
currentCount++;
}
}
This code compiles and I would like to know why in terms of static access privledges.
I have found this from The Java Tutorials
Instance methods can access instance variables and instance methods directly.
Instance methods can access class variables and class methods directly.
Class methods can access class variables and class methods directly.
Class methods cannot access instance variables or instance methods directly—they must use an object reference. Also, class methods cannot use the this keyword as there is no instance for this to refer to.
So the answer is yes, non-static methods CAN modify static variables
No, any non-static method has access to static members. The only way this would be false is if the non-static context did not have access to the static member (ex. the static member is private to a class and the non-static code is not in that class). static variables exist to provide an instance free variable/method, so for example if we have a Game class and a highscore variable, the highscore would be static (accessible without an instance), and after every game (an instance of the Game class) completes we could alter the highscore from our non-static context if our score is greater than the high score.
Non static methods can access static variables.
Static methods can access only static variables or methods directly without creating object.ex:public static void main(String arg[])
Non-Static Methods can access both Static Variables & Static Methods as they Members of Class
Demo Code
public class Static_Class {
protected static String str;
private static int runningLoop;
static{
str = "Static Block";
}
/**
* Non-Static Method Accessing Static Member
*/
public void modifyStaticMember(){
str = "Non-Static Method";
}
/**
* Non-Static Method invoking Static Method
*/
public void invokeStaticMethod(){
String[] args = {};
if(runningLoop == 0){
runningLoop++;
main(args);
}
//Exiting as it will lead to java.lang.StackOverflowError
System.exit(0);
}
public static void main(String[] args) {
Static_Class instance = new Static_Class();
System.out.println(str);
instance.modifyStaticMember();
// Changed Value persists
System.out.println(str);
//Invoking Static Method
instance.invokeStaticMethod();
}
}
Look at it this way. A static variable can be accessed in many ways. One of the most common is to precede the var name with the class name, since static vars are per class.
Since you refer to this variable in the same class, you are exempt from having to precede it with the class name. It does not matter where you call the static variable.
Also this is a private static var not accessible by any other class.
Static variables are class variable not instance or local variable . that is why we can use static variable in non static method also. and static variables are not per object . static variables have one copy that will be used in entire program.
Static methods cannot modify Non-static fields since - For using a Non-Static field (outside the class) you must instantiate a class object,
But for using a Static method there is no need for object instantiation at all.
This is why it's not reasonable for a Non-Static Method (which not demands an object instantiation)
to modify a field that should be instantiated.
For this - Static methods can touch only static fields (or call other static methods).
But as you mentioned the other way around is possible,
A Non-Static method can modify a static field which is static for all objects of its class.
Static members are not instance members , these are shared by class , so basically any instance method can access these static members .
Yes, a static method can access a non-static variable. This is done by creating an object to the class and accessing the variable through the object. In the below example main is a static method which accesses variable a which is a non-static variable.
demo code:
public class Sample {
private int a;
void method()
{
System.out.println("i am a private method");
}
public static void main(String[] args)
{
Sample sample=new Sample();
sample.a=10;
System.out.println(sample.a);
}
}

Why non-static variable cannot be reference from a static context - reg [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
non-static variable cannot be referenced from a static context (java)
public class DemoJava {
public class Hello {
void fun()
{
System.out.println("This is static fun man!!");
}
}
public static void main(String[] args) {
Hello hello = new Hello();
hello.fun();
}
}
In this example it will give me an error since I am trying to access a non-static class from a static method. Fine. For instance, if I have the same Hello class in another file and I do the same thing it does not give me an error.
Even in that case we are trying to access non-static class from static method. But that doesn't give any error. Why?
In this example it will give me an error since I am trying to access a non-static class from a static method.
No, it will give you an error because you're trying to create an instance of an inner class (which implicitly has a reference to an instance of the enclosing class) when you don't have an instance of the enclosing class.
The problem isn't the call to fun() - it's the constructor call.
For example, you can fix this by using:
DemoJava demo = new DemoJava();
Hello hello = demo.new Hello();
Or you could just make it a nested but not inner class, by changing the class declaration to:
public static class Hello
Read section 8.1.3 of the JLS for more information on inner classes, and section 15.9.2 for determining enclosing instances for a class instance creation expression:
Otherwise, C is an inner member class (§8.5), and then:
If the class instance creation expression is an unqualified class instance creation expression, then:
If the class instance creation expression occurs in a static context, then a compile-time error occurs.
yes, it will give you error, correct way of doing it is
public class DemoJava {
public class Hello {
void fun()
{
System.out.println("This is static fun man!!");
}
}
public static void main(String[] args) {
DemoJava demoJava = new DemoJava();
Hello hello = demoJava.new Hello(); //you need to access your inner class through instance object
hello.fun();
}
}
you have to create an instance of Outer class in-order to create the instance of your inner class.
From Documentation:
To instantiate an inner class, you must first instantiate the outer
class.
syntax:
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
DemoJava demoInst=new DemoJava();
Hello hello = demoInst.new Hello();
hello.fun();
Make class Hello static
public static class Hello {
void fun()
{
System.out.println("This is static fun man!!");
}
}
Your inner class Hello dous not need access to an instance of the outer class DemoJava therefore it can be made static.
You can always call the static functions of a class without having an instance
Hello.fun();
should work!

Android vs Java causing some confusion for me when creating methods

I was helping a friend on his Java homework today, and I guess I didn't realize there being a difference between plain Java and Java in Android. Quick write up of the program:
public class myClass{
public static void Main (String[] args){
doThis();
}
public void doThis(){
System.out.println("Did this");
}
}
But when running that, I got a complaint that I needed to make the doThis() method to be static. Why is that? When I develop some basic things in Android, I never have to use the static keyword.
Note: This could stem from the fact that I'm intimidated by what static actually means.
Why is that?
Because Main() is static.
If Main() was an instance method, and you had called Main() on an instance of myClass (e.g., new myClass), then doThis() could also be an instance method. Or, if your static Main() created an instance of myClass, it could call doThis() on that instance.
When I develop some basic things in Android, I never have to use the static keyword.
That is because your entry points in Android tend to be instance methods on components (e.g., onCreate() of an Activity.
A static method is a method that is not invoked on any Object instance. A non-static method belongs to an object, and needs an object instance in order to be invoked. It's thus not legal to call an instance method from static method, since the static method is not invoked on any object.
You need to instanciate an object to call an instance method:
public static void main(String[] args){
MyClass object = new MyCLass();
object.doThis();
}
public void doThis(){
System.out.println("Did this");
}
Android code is Java code, and has exactly the same rule.
Read the Java tutorial about instance and static members.
The issue is you need to rewrite it like so:
public class MyClass{ //fixed camel casing, classes start with upper case
public static void main (String[] args){ //fixed lettering
MyClass mc = new MyClass();
mc.doThis();
}
public void doThis(){
System.out.println("Did this");
}
}
This is nothing special about the difference between Android and Java, both will fail. The problem is you are trying to reference a non-static method from a static context, this could cause issues, as static indicates that the class does not need to be instantiated to invoke a function.
Static methods can be called without having an instance of the owning class, so therefore you can do:
myClass.doThis();
Since your doThis() method isn't static, you'd have to create an instance object like so:
myClass instance = new myClass();
instance.doThis();
The main() method that is calling your doThis() method is a static method, and an instance of myClass isn't required for it to be called. This means that any methods being called by your main method must be static, or called on an instance object (see 2nd example above).

Categories