what is the name of such invocation "variable.methodName(data);" ? [duplicate] - java

See the code snippets below:
Code 1
public class A {
static int add(int i, int j) {
return(i + j);
}
}
public class B extends A {
public static void main(String args[]) {
short s = 9;
System.out.println(add(s, 6));
}
}
Code 2
public class A {
int add(int i, int j) {
return(i + j);
}
}
public class B extends A {
public static void main(String args[]) {
A a = new A();
short s = 9;
System.out.println(a.add(s, 6));
}
}
What is the difference between these code snippets? Both output 15 as an answer.

A static method belongs to the class itself and a non-static (aka instance) method belongs to each object that is generated from that class. If your method does something that doesn't depend on the individual characteristics of its class, make it static (it will make the program's footprint smaller). Otherwise, it should be non-static.
Example:
class Foo {
int i;
public Foo(int i) {
this.i = i;
}
public static String method1() {
return "An example string that doesn't depend on i (an instance variable)";
}
public int method2() {
return this.i + 1; // Depends on i
}
}
You can call static methods like this: Foo.method1(). If you try that with method2, it will fail. But this will work: Foo bar = new Foo(1); bar.method2();

Static methods are useful if you have only one instance (situation, circumstance) where you're going to use the method, and you don't need multiple copies (objects). For example, if you're writing a method that logs onto one and only one web site, downloads the weather data, and then returns the values, you could write it as static because you can hard code all the necessary data within the method and you're not going to have multiple instances or copies. You can then access the method statically using one of the following:
MyClass.myMethod();
this.myMethod();
myMethod();
Non-static methods are used if you're going to use your method to create multiple copies. For example, if you want to download the weather data from Boston, Miami, and Los Angeles, and if you can do so from within your method without having to individually customize the code for each separate location, you then access the method non-statically:
MyClass boston = new MyClassConstructor();
boston.myMethod("bostonURL");
MyClass miami = new MyClassConstructor();
miami.myMethod("miamiURL");
MyClass losAngeles = new MyClassConstructor();
losAngeles.myMethod("losAngelesURL");
In the above example, Java creates three separate objects and memory locations from the same method that you can individually access with the "boston", "miami", or "losAngeles" reference. You can't access any of the above statically, because MyClass.myMethod(); is a generic reference to the method, not to the individual objects that the non-static reference created.
If you run into a situation where the way you access each location, or the way the data is returned, is sufficiently different that you can't write a "one size fits all" method without jumping through a lot of hoops, you can better accomplish your goal by writing three separate static methods, one for each location.

Generally
static: no need to create object we can directly call using
ClassName.methodname()
Non Static: we need to create a object like
ClassName obj=new ClassName()
obj.methodname();

A static method belongs to the class
and a non-static method belongs to an
object of a class. That is, a
non-static method can only be called
on an object of a class that it
belongs to. A static method can
however be called both on the class as
well as an object of the class. A
static method can access only static
members. A non-static method can
access both static and non-static
members because at the time when the
static method is called, the class
might not be instantiated (if it is
called on the class itself). In the
other case, a non-static method can
only be called when the class has
already been instantiated. A static
method is shared by all instances of
the class. These are some of the basic
differences. I would also like to
point out an often ignored difference
in this context. Whenever a method is
called in C++/Java/C#, an implicit
argument (the 'this' reference) is
passed along with/without the other
parameters. In case of a static method
call, the 'this' reference is not
passed as static methods belong to a
class and hence do not have the 'this'
reference.
Reference:Static Vs Non-Static methods

Well, more technically speaking, the difference between a static method and a virtual method is the way the are linked.
A traditional "static" method like in most non OO languages gets linked/wired "statically" to its implementation at compile time. That is, if you call method Y() in program A, and link your program A with library X that implements Y(), the address of X.Y() is hardcoded to A, and you can not change that.
In OO languages like JAVA, "virtual" methods are resolved "late", at run-time, and you need to provide an instance of a class. So in, program A, to call virtual method Y(), you need to provide an instance, B.Y() for example. At runtime, every time A calls B.Y() the implementation called will depend on the instance used, so B.Y() , C.Y() etc... could all potential provide different implementations of Y() at runtime.
Why will you ever need that? Because that way you can decouple your code from the dependencies. For example, say program A is doing "draw()". With a static language, thats it, but with OO you will do B.draw() and the actual drawing will depend on the type of object B, which, at runtime, can change to square a circle etc. That way your code can draw multiple things with no need to change, even if new types of B are provided AFTER the code was written. Nifty -

A static method belongs to the class and a non-static method belongs to an object of a class.
I am giving one example how it creates difference between outputs.
public class DifferenceBetweenStaticAndNonStatic {
static int count = 0;
private int count1 = 0;
public DifferenceBetweenStaticAndNonStatic(){
count1 = count1+1;
}
public int getCount1() {
return count1;
}
public void setCount1(int count1) {
this.count1 = count1;
}
public static int countStaticPosition() {
count = count+1;
return count;
/*
* one can not use non static variables in static method.so if we will
* return count1 it will give compilation error. return count1;
*/
}
}
public class StaticNonStaticCheck {
public static void main(String[] args){
for(int i=0;i<4;i++) {
DifferenceBetweenStaticAndNonStatic p =new DifferenceBetweenStaticAndNonStatic();
System.out.println("static count position is " +DifferenceBetweenStaticAndNonStatic.count);
System.out.println("static count position is " +p.getCount1());
System.out.println("static count position is " +DifferenceBetweenStaticAndNonStatic.countStaticPosition());
System.out.println("next case: ");
System.out.println(" ");
}
}
}
Now output will be:::
static count position is 0
static count position is 1
static count position is 1
next case:
static count position is 1
static count position is 1
static count position is 2
next case:
static count position is 2
static count position is 1
static count position is 3
next case:

If your method is related to the object's characteristics, you should define it as non-static method. Otherwise, you can define your method as static, and you can use it independently from object.

Static method example
class StaticDemo
{
public static void copyArg(String str1, String str2)
{
str2 = str1;
System.out.println("First String arg is: "+str1);
System.out.println("Second String arg is: "+str2);
}
public static void main(String agrs[])
{
//StaticDemo.copyArg("XYZ", "ABC");
copyArg("XYZ", "ABC");
}
}
Output:
First String arg is: XYZ
Second String arg is: XYZ
As you can see in the above example that for calling static method, I didn’t even use an object. It can be directly called in a program or by using class name.
Non-static method example
class Test
{
public void display()
{
System.out.println("I'm non-static method");
}
public static void main(String agrs[])
{
Test obj=new Test();
obj.display();
}
}
Output:
I'm non-static method
A non-static method is always be called by using the object of class as shown in the above example.
Key Points:
How to call static methods: direct or using class name:
StaticDemo.copyArg(s1, s2);
or
copyArg(s1, s2);
How to call a non-static method: using object of the class:
Test obj = new Test();

Basic difference is non static members are declared with out using the keyword 'static'
All the static members (both variables and methods) are referred with the help of class name.
Hence the static members of class are also called as class reference members or class members..
In order to access the non static members of a class we should create reference variable .
reference variable store an object..

Simply put, from the point of view of the user, a static method either uses no variables at all or all of the variables it uses are local to the method or they are static fields. Defining a method as static gives a slight performance benefit.

Another scenario for Static method.
Yes, Static method is of the class not of the object. And when you don't want anyone to initialize the object of the class or you don't want more than one object, you need to use Private constructor and so the static method.
Here, we have private constructor and using static method we are creating a object.
Ex::
public class Demo {
private static Demo obj = null;
private Demo() {
}
public static Demo createObj() {
if(obj == null) {
obj = new Demo();
}
return obj;
}
}
Demo obj1 = Demo.createObj();
Here, Only 1 instance will be alive at a time.

- First we must know that the diff bet static and non static methods
is differ from static and non static variables :
- this code explain static method - non static method and what is the diff
public class MyClass {
static {
System.out.println("this is static routine ... ");
}
public static void foo(){
System.out.println("this is static method ");
}
public void blabla(){
System.out.println("this is non static method ");
}
public static void main(String[] args) {
/* ***************************************************************************
* 1- in static method you can implement the method inside its class like : *
* you don't have to make an object of this class to implement this method *
* MyClass.foo(); // this is correct *
* MyClass.blabla(); // this is not correct because any non static *
* method you must make an object from the class to access it like this : *
* MyClass m = new MyClass(); *
* m.blabla(); *
* ***************************************************************************/
// access static method without make an object
MyClass.foo();
MyClass m = new MyClass();
// access non static method via make object
m.blabla();
/*
access static method make a warning but the code run ok
because you don't have to make an object from MyClass
you can easily call it MyClass.foo();
*/
m.foo();
}
}
/* output of the code */
/*
this is static routine ...
this is static method
this is non static method
this is static method
*/
- this code explain static method - non static Variables and what is the diff
public class Myclass2 {
// you can declare static variable here :
// or you can write int callCount = 0;
// make the same thing
//static int callCount = 0; = int callCount = 0;
static int callCount = 0;
public void method() {
/*********************************************************************
Can i declare a static variable inside static member function in Java?
- no you can't
static int callCount = 0; // error
***********************************************************************/
/* static variable */
callCount++;
System.out.println("Calls in method (1) : " + callCount);
}
public void method2() {
int callCount2 = 0 ;
/* non static variable */
callCount2++;
System.out.println("Calls in method (2) : " + callCount2);
}
public static void main(String[] args) {
Myclass2 m = new Myclass2();
/* method (1) calls */
m.method();
m.method();
m.method();
/* method (2) calls */
m.method2();
m.method2();
m.method2();
}
}
// output
// Calls in method (1) : 1
// Calls in method (1) : 2
// Calls in method (1) : 3
// Calls in method (2) : 1
// Calls in method (2) : 1
// Calls in method (2) : 1

Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier.
i.e. class human - number of heads (1) is static, same for all humans, however human - haircolor is variable for each human.
Notice that static vars can also be used to share information across all instances

Related

Method override not working properly in Java [duplicate]

I have a simple question that I just can't figure out a good answer for. Why does the following Java program display 20? I would prefer a detailed response if possible please.
class Something{
public int x;
public Something(){
x=aMethod();
}
public static int aMethod(){
return 20;
}
}
class SomethingElse extends Something{
public static int aMethod(){
return 40;
}
public static void main(String[] args){
SomethingElse m;
m=new SomethingElse();
System.out.println(m.x);
}
}
Because polymorphism only applies to instance methods.
The static method aMethod invoked here
public Something(){
x=aMethod();
}
refers to the aMethod declared in Something.
The inheritance for static methods works differently then non-static one. In particular the superclass static method are NOT overridden by the subclass. The result of the static method call depends on the object class it is invoke on. Variable x is created during the Something object creation, and therefore that class (Something) static method is called to determine its value.
Consider following code:
public static void main(String[] args){
SomethingElse se = new SomethingElse();
Something sg = se;
System.out.println(se.aMethod());
System.out.println(sg.aMethod());
}
It will correctly print the 40, 20 as each object class invokes its own static method. Java documentation describes this behavior in the hiding static methods part.
Because int x is declared in the class Something. When you make the SomethingElse object, you first make a Something object (which has to set x, and it uses the aMethod() from Something instead of SomethingElse (Because you are creating a Something)). This is because aMethod() is static, and polymorphism doesn't work for static methods. Then, when you print the x from m, you print 20 since you never changed the value of x.

Why is my instance variable accessible without an instance?

My understanding of the Instance variables is that they are created when an object is created. If that is true then why can print the variable "data"? Shouldn't I have to create an object of class JavaTesting first?
public class JavaTesting
{
static int a = 1;
private int data = 99;
#Test
public void f1()
{
System.out.println("Print a = "+a);
System.out.println("Print data = "+data);
}
}
Your method f1() is not a static method. This means it can only be called on an instance. Whatever method is calling f1() is probably creating an instance of JavaTesting first. If you made f1() static, your IDE would probably have a fit and start coughing up red flags.

Difference between Calling Static function from Object and Class itself

I was learning singleton design pattern and I did understand the concept. However, I have a doubt in the following code : -
class Token
{
private static int i = 5;
private static Token obj = new Token();
//Private Constructor
private Token()
{
}
//Returning the singleton object
public static Token getObject()
{
return obj;
}
public static int getValue()
{
return i;
}
}
public class TestMain
{
public static void main(String args[])
{
Token obj = Token.getObject();
System.out.println("Without object " + Token.getValue());
System.out.println("With object " + obj.getValue());
}
}
The instance variable i gets printed in both the cases -
Without object 5
With object 5
What is the difference between the two ways of getting instance variable and which one is recommended?
i is a static variable that belongs to class Token so it'll have the same value for all objects that are of type Token.
For all practical purposes, obj.getValue() is the same as Token.getValue() and you could use either, but for better readability, use Token.getValue() as it reinforces the idea that the static variable i and static method getValue() belong to the class as a whole and not to certain objects of that class.
In fact in obj you have reference to your singleton. So calling Token.getValue() reference to same obj as obj.getValue()
There is little difference, for instance access you need the actual instance, which you don't always have.
As for preference it depends on who you ask. For me static fields and methods should be accessed using the class not instance - this clearly shows that it is static.

Why do print statements execute in this order when using initializers, constructors and method calls?

This is the code I'm running , the output of this code is 4 2 1 3 , could someone please explain why the result was printed in this order.
public class goFuncTest {
goFuncTest()
{
System.out.print("1 ");
}
{
System.out.print("2 ");
}
public static void main(String[] args)
{
new goFuncTest().go();
}
void go()
{
System.out.print("3 ");
}
static
{
System.out.print("4 ");
}
}
Based on your recent question edit, your output will be 4 2 1 3. The static initializers are run first, then the instance initializers. If you had multiple initializers of the same type, they would execute in the order they appear in the class.
// static initializer first
static {
System.out.print("4 ");
}
// then instance initializer
{
System.out.print("2 ");
}
Next the constructor fires up, which gives you:
goFuncTest()
{
System.out.print("1 ");
}
finally the method is invoked:
void go()
{
System.out.print("3 ");
}
As JB Nizet pointed out in first comment, result should be 2,4,3,1.
And coming to the order, static blocks executes first and then initialization blocks. In your code there are no static blocks and only inti blocks.
The order of initialization block execution is the order they placed in source code -2,4.
And remaining two results as per constructor and method call. 1,3
Now you can see the answer right ?
Reason:
You have instance block which gets executed in sequence in which appear in your class definition. So 2 comes first and then 4 and hence output 2 4
Next you are calling new goFuncTest(), which is going to call your constructor and hence you will see 1 in the output.
Now on your instance you are calling go method which prints 3.
It seems the main confusion is just due to not understanding the various blocks that a class can have;
this answer gives a nice example and explanation;
Here's the code they give:
public class Test {
static int staticVariable;
int nonStaticVariable;
// Static initialization block:
// Runs once (when the class is initialized).
static {
System.out.println("Static initalization.");
staticVariable = 5;
}
// Instance initialization block:
// Runs before the constructor each time you instantiate an object
{
System.out.println("Instance initialization.");
nonStaticVariable = 7;
}
public Test() {
System.out.println("Constructor.");
}
public static void main(String[] args) {
new Test();
new Test();
}
}
This class has a static initialiser, an instance initialisation block, a constructor, and a class method.
static initialiser: static {...}
instance initialiser: {...}
constructor: Public ClassName(){...}
class method: Public Static Whatever classMethod(String[] args){...}
Each of these is called under different circumstances; the static initialiser is called when the class is loaded, there's no other way to call it, you can't even do it via reflection, as it's never represented by a method instance, it is called by the JVM.
the instance initialiser is called whenever you create an instance of the class - before the constructor.
You can have multiple static initialisers, and multiple instance initialisers, and they are executed in the order they appear in the code.
constructor and class method you presumably already know about.
In your example, it would probably be a little more helpful to rearrange the code slightly, to better reflect that hierarchy;
public class goFuncTest {
//static instance initialiser
static {
System.out.print("4 ");
}
//instance initialiser
{
System.out.print("2 ");
}
//Constructor
goFuncTest(){
System.out.print("1 ");
}
//Class method
void go(){
System.out.print("3 ");
}
public static void main(String[] args){
new goFuncTest().go();
}
}
(editted to add in the static keyword)

Can not make static reference to non static method? [duplicate]

This question already has answers here:
Static Classes In Java
(14 answers)
Closed 3 years ago.
So, in short. I have two classes.
package rpg;
public class Engine {
public void main(String args[]) {
Start.gameStart();
System.out.println(menuResult);
}
}
and
package rpg;
public class Start {
int menuResult = 3;
public int gameStart()
{
return menuResult;
}
public int getMenuResult()
{
return Start.menuResult;
}
}
It keeps throwing up the error 'Cannot make static reference to non-static method gameStart()'.
I'm sure I'm missing something simple, but can't find it.
Thanks!
You need to create instance of Start class and call gameStart() method on that instance because gameStart() is instance method not static method.
public void main(String args[]) {
new Start().gameStart();
..................
}
Only static methods can be accessed by using class name as perfix.
public int gameStart() <--- Instance method not static method
call it on instance
Start start = new Start();
start.gameStart();
So finally your classes should look like below
public static void main(String args[]) {
Start start = new Start();
start.gameStart();
System.out.println(start.getMenuResult());
}
public class Start {
private int menuResult = 3;
public int gameStart() {
return this.menuResult;//Don't know why there are two methods
}
public int getMenuResult() {
return this.menuResult;
}
}
first of all the main method should be
public static void main(String args[]) {
}
I assume you can have multiple games, and hence you should be able to start multiple instances so you should create a non static class that can be created and then actions performed against.
to answer your original question, you need to have a static variable that have static getters and setters..
public class Start {
private static int menuResult = 3;
public static int gameStart()
{
return menuResult;
}
public static int getMenuResult()
{
return Start.menuResult;
}
If you need the method to be static, just add the keyword static in the function definition. That would get rid of the error. But if you want to keep the class Start the way it is, then you should create an instance of Start in the main function and then call the method. Hope that helps!
you are trying to invoke a method on its class name. you should be creating a new object and invoke its method
public void main(String args[]) {
new Start().gameStart();
System.out.println(menuResult);
}
Start.gameStart() refers to a method which would be public static int gameStart() because Start is the class and not an instance of the object.
If you declare a method on an object, you need to apply it to instance of the object and not its class.
When to use static or instanciated methods ?
instanciated : whenever you need to apply the method to the object you're in. example : mycake.cook();
static : when the actions you do inside your method have nothing to do with an object in particular. example : Cake.throwThemAll();
mycake is an instance of a Cake, declared this way : Cake mycake = new Cake();
Cake is the class representing the object.
You should, i guess, have a read at some object oriented programmation course if you still have a doubt about objects, classes and instances.
While Other answers are Correct , that remains the Question that Why you Can't access Instance
method Directly from Class name , In Java all static (methods , fields) bind with Class Name and when Class Is Loading to the Memory (Stack) all static members are Loading to the Stack , and this time Instance Method is not visible to Class. instance Method will Load into Heap portion in the memory and can only be access by Object references .

Categories