java- "new" operator in static method - java

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.

Related

Instance methods can access instance methods directly. What does this mean?

After going through Java documentation I understand that a field declared with 'static' keyword is class variable (or static field) and similarly when using 'static' during method declaration, is a static method (or class method). Class variable and Class methods are reference by class name itself.
Read this and this topics however could not understand following sentences from Java documentation.
What does it mean when it says.....
Not all combinations of instance and class variables and methods are allowed:
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.
The Java doc clearly explains about Class variables and Class methods but above 3 points are confusing to me.
Example Execution
1.Instance methods can access instance variables and instance methods directly.
Some Info:
Instance method are methods which require an object of its class to be
created before it can be called.To invoke a instance method, we have to
create an Object of the class in within which it defined.
Instance variables are declared in a class, but outside a method, constructor
or any block.
class Example1 {
int a = 100; // instance variable
public void printData() { // this an instance method called using an object of class Example1
getData(); // accessing another instance method directly without any object
}
public void getData() {
System.out.println(a); // accessing instance variable 'a' directly without any object
}
}
public class InstanceDemo {
public static void main(String[] args) {
Example1 obj1 = new Example1();
obj1.printData(); // will print 100
}
}
2.Instance methods can access class variables and class methods directly.
Class variables also known as static variables are declared with the static
keyword in a class, but outside a method, constructor or a block.
class Example2 {
static int a = 20; // 'static' / class variable
public void printData() { // instance method
setData(); // accessing class method directly
System.out.println(a); // accessing class variable directly
}
public static void setData() { // class method 'static'
a = 200; // setting value of class variable 'a'
}
}
public class InstanceDemo {
public static void main(String[] args) {
Example2 obj2 = new Example2();
obj2.printData(); // will print 200
}
}
3.Class methods can access class variables and class methods directly.
Static methods are the methods in Java that can be called without creating an
object of class. They are referenced by the class name itself or reference to
the Object of that class.
Memory Allocation: They are stored in Permanent Generation space of heap as
they are associated to the class in which they reside not to the objects of
that class. But their local variables and the passed argument(s) to them are
stored in the stack. Since they belong to the class so they can be called to
without creating the object of the class.
class Example3 {
static int a = 300;
public static void printData() {
getData(); // accessing class method
}
public static void getData() {
System.out.println(a); // accessing class variable 'a'
}
}
public class InstanceDemo {
public static void main(String[] args) {
//calling class method : class method are called using class name.
Example3.printData(); // will print 300
}
}
I think you just need to practice programming, so you can experience how the language works. Understanding the quirks of static access is one of the hardest things to grasp initially. Static members are generally geared towards providing class utility.
An instance method gets a pointer to the instance it's operating on, on the stack, therefore it can access the members of the instance. A static method isn't associated with any particular instance. There's no 'this' reference, thus it can't access instance members.
Instance methods can access instance variables and instance methods
directly.
This means a method that doesn't have a static modifier i.e. an instance method can access any non-static variable as well as call any non-static method.
Instance methods can access class variables and class methods
directly.
This means a method that doesn't have a static modifier i.e. an instance method can access a static variable or call a method with the static modifier.
Class methods can access class variables and class methods directly.
This means a static method can access any static variable as well as call any other method that has a static modifier.
To put it simply, an instance method i.e. a method without the static modifier can access both a static variable as well as a non-static variable and it can also directly call a static method and a non-static method.
On the other hand, a static method can only access static variables and call static methods. it cannot, however, access an instance variable or instance methods directly without an object.

What is the purpose of creating static object in 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.

Java why static prints out text first than method

Just wondering why static is always the one that will print out first rather than a method.
Code:
public class TestMe {
static {
System.out.println("D");
}
{
System.out.println("B");
}
public void printMe() {
System.out.println("Z");
}
public static void main(String []args) {
new TestMe().printMe();
}
}
Output:
D
B
Z
static blocks are executed when a class is first initialized (initialization of a class happens once it is loaded ) so they execute earlier than instance level blocks / methods (executed after creating an object)
You have two types of initializer block in your class
one is static initializer which is executed by the time the class is initialized
8.7. Static Initializers
A static initializer declared in a class is executed when the class is initialized
8.6. Instance Initializers
two is the Instance Initializers which is executed when instance of the class is already create
An instance initializer declared in a class is executed when an instance of the class is created
Those are from JLS documentation
So static initializer will be called directly when class is initialized vs Instance Initializers that is called when instance of that class is already created thus static initializer is executed first.
Because static blocks are executed when the class is loaded.
because that gets executed when class initializes it self
Also See
doc: Initializing Fields

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

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