i am a new to java . there is something new pops up called public final void. what does that do ? what is the difference between public static void and public final void? I would be greatly appreciated from guys!
public final void method() {}
This method is final, and so can't be overrided in a subclass.
public static void method() {}
This method is static, and so is class-scoped. You can't use class attribute in this method (unless if they are static), and you call it using MyClass.method() instead of anInstance.method().
Finally, void is the return type of the function (meaning the method returns nothing) and public is an access modifier.
Related questions:
About access modifier,
About final,
About when to use static.
That must be a part of method:
public - meaning it could be accessible by any other object
static - meaning it could be accessed by class name in addition to object as well.
void - meaning that method wont return any value. It will do some operations
within the method.
final - Meaning you cant override the method in your sub class.
The final keyword is used for variables when they are constant, their value can be set only once, furthermore a final method cannot be subclassed.
static members belong to the class instead of a specific instance.
When you declare a method final, subclasses of your class will not be able to override it.
When you declare a method static you can call it without creating an object of class.
Related
I found such an usage of protected modifier while searching for a solution for my other question: Ignoring case in strings with unitils ReflectionComparator
In the org.unitils.reflectionassert.ReflectionComparatorFactory class there is a method with the signature:
protected static List<Comparator> getComparatorChain(Set<ReflectionComparatorMode> modes)
But this is only a particular case.
After all we can always extend such any non-final class and "override" it's static protected method with the new public modifier. Say, we have a class A:
public class A {
protected static void test() {
// do some stuff
}
}
and want to use it in another package:
public class UseA {
private static class MyA extends A {
public static void test() {
A.test();
}
}
void useA() {
// A.test(); compile error, sure
MyA.test();
}
}
I concentrate my question on a general situation when some static method was declared as protected. I'm not asking about non-static fields or methods, because in some cases class can have a private constructor or a very complicated constructor with lots special params. But what is the purpose of such "hiding" static methods if entire class isn't final? Is such usage an OOP mistake or just a very weak "protection"?
But what is the purpose of such "hiding" static methods if entire class isn't final?
A protected static method would allow you to provide "utility" type functionality to derived classes, without exposing them in the public API where they might not make sense on their own.
I don't know the implementation of the getComparatorChain method you reference, but I imagine it's such a method. It would be marked static if it's not tied to any specific instance, and marked protected so as not to be a part of the public API, but also to allow derived classes to re-use the utility method in it's own implementation.
Overriding a static method reference means hiding it's implementation. See: Java Documentation's Overriding and Hiding Methods
Static Methods
If a subclass defines a static method with the same signature as a static method in the superclass, then the method in the subclass hides the one in the superclass.
The distinction between hiding a static method and overriding an instance method has important implications:
The version of the overridden instance method that gets invoked is the one in the subclass.
The version of the hidden static method that gets invoked depends on whether it is invoked from the superclass or the subclass.
I am confused by the behaviour of the static method when it is overridden in the subclass.
Below is the code:
public class SuperClass {
public static void staticMethod() {
System.out.println("SuperClass: inside staticMethod");
}
}
public class SubClass extends SuperClass {
//overriding the static method
public static void staticMethod() {
System.out.println("SubClass: inside staticMethod");
}
}
public class CheckClass {
public static void main(String[] args) {
SuperClass superClassWithSuperCons = new SuperClass();
SuperClass superClassWithSubCons = new SubClass();
SubClass subClassWithSubCons = new SubClass();
superClassWithSuperCons.staticMethod();
superClassWithSubCons.staticMethod();
subClassWithSubCons.staticMethod();
}
}
Below is the output which we are getting :
1) SuperClass: inside staticMethod
2) SuperClass: inside staticMethod
3) SubClass: inside staticMethod
Why static method of superclass gets called here in the second case?
If method is not static, then according to polymorphism, method of the subclass is called when subclass object is passed on runtime.
static method resolution is always based on the Reference type.
The code
superClassWithSuperCons.staticMethod();
superClassWithSubCons.staticMethod();
subClassWithSubCons.staticMethod();
is converted to this after compilation
SuperClass.staticMethod();
SuperClass.staticMethod();
SubClass.staticMethod();
Accroding to this it is the call to SuperClass method not the subclass method.So you are getting the output of SuperClass method.
A method declared static cannot be overridden but can be re-declared. That's the answer.
A static method is not associated with any instance of a class so the concept is not applicable. Try the same with not static and you'll see the difference.
Your question is duplicated actually:
Why doesn't Java allow overriding of static methods?
Interesting question. I'm not familiar with the underlying mechanisms, but it seems that for static methods, the declared type (in your middle example, SuperClass), not the actual type SubClass is considered for resolving the method call. It actually makes sense because you're not looking at the actual instance of an object when calling a static function.
Static methods are redefined not overridden...
If you try to override the static method then it will be treated as a non overridden method of the sub class.
Static methods will be called based on the type of the reference not the object created.
For more information visit the page.
http://javaunturnedtopics.blogspot.in/2016/07/static-methods-are-redefined-not.html
So I know that in Java when you have a static method you are supposed to call it with the format ClassName.method() rather than use the same structure as you would for instance methods, namely:
ClassName myObject = new ClassName();
myObject.method();
However, if you were to do it this way it would still be valid code and would work. Let's say I decide to do this where the method in question is static, and have the following setup:
public SuperClass {
public static int foo(int x) {
return x;
}
}
public SubClass extends SuperClass {
public static int foo(int x) { // Overriding foo() in SuperClass
return x + 1;
}
}
public MyDriver {
public static void main(String[] args) {
SuperClass myObject = new SubClass(); // Upcasting.
System.out.println(myObject.foo(5)); // This should polymorphically print 6
}
}
What prints out on the screen, however, is 5 rather than 6. Why?
Static methods apply only to the class they are defined in, and they cannot be overridden.
When you call myObject.foo(5), you are calling SuperClass.foo(5) in reality, because you declared myObject as a SuperClass, regardless of whether you instantiated it as one.
The proper way to call a static method is to call it directly from the class it is declared in, so if you wanted to call SubClass.foo(), you must call it from an explicitly declared SubClass instance (meaning no upcasting), or you need to call SubClass.foo() like so.
The simple answer is that calling static methods from instances evaluates to calling those same methods from the declared type with no instance rather than the instance type.
I am not certain of this, but I would not be surprised if when the code is compiled into byte-code, that the instance static method call would actually be compiled into a direct call to the declared type.
Edit: An upvote brought my attention back to this and I cleaned up the explanation to make it more clear and fix some negligible grammatical mistakes on my part. I hope this helps future readers.
Using instances of a class to call that class's static methods is something you should avoid, since it can cause confusion. If you need to call any method polymorphically, make it an instance method. You cannot polymorphically call a static method. The reason the SuperClass invocation is called is because that is the apparent class of myObject at compile-time. This effect can also be seen in the following scenario:
public void doSomething(SuperClass param) {
System.out.println("SuperClass");
}
public void doSomething(SubClass param) {
System.out.println("SubClass");
}
public void test() {
SuperClass myObject = new SubClass();
doSomething(myObject);
}
If test() is called, SuperClass will be printed.
Static methods don't depends on the instance, they belong to the class and only to the class, in fact if you have a static method you'll always access to one unique instance always.
myObject.foo(5)
is only a shortcut, what you really are doing is
SuperClass.foo(5)
Static methods are treated as global by the JVM, they are not bound to an object instance at all. By the way, you can only overload static methods, but you can not override. So check for "Oracle Documentation for Overriding and Hiding Documents".
Defining a Method with the Same Signature as a Superclass's Method:
-----------------------------------------Superclass Instance MethodSuperclass Static Method
Subclass Instance Method Overrides Generates a compile-time error
Subclass Static Method Generates a compile-time error Hides
class Sub {
static int y;
public static void foo() {
this.y = 10;
}
}
I understand that this represents the object invoking the method and that static methods are not bound to any object. But in the above mentioned case, the variable y is also static.
If we can invoke static method on class object, why can't we allow static methods to set the static variables of the class.
What is the purpose of this additional constraint?
Because this refers to the object instance. There is no object instance in a call of a static method. But of course you can access your static field (only the static ones!). Just use
class Sub {
static int y;
public static void foo() {
y = 10;
}
}
If you want to make sure you get the static field y and not some local variable with the same name, use the class name to specify:
class Sub {
static int y;
public static void foo(int y) {
Sub.y = y;
}
}
The main reason why we can not use "this" in static method context:-
this :- "this" means current class OBJECT , so its clear that "this" only come in
the picture once we intended to create an Object of that class.
static method:- there is no need to create an object in order to use static method.
means "instance" or object creation doesn't any sense with "static" as per Java rule.
So There would be contradiction,if we use both together(static and this) .
That is the reason we can not use "this" in static method.
this is referring to this instance of the object Sub. As the method is static, there is not an instance of Sub.
To make your code work write it like this:
class Sub {
static int y;
public static void foo() {
Sub.y = 10;
}
}
You can set static fields in static methods, but you don't have access to this in static method because this represents the current instance of the object, and in a static method you have no instance.
This means "this" object but there isn't one. In your case you can use the class name as #tibtof suggests.
"this" keyword is only applicable where an instance of an object is created. And in static method no instance is created because static method belongs to class area.
There is no problem with static methods setting values for static fields.
The only issue is usage of this keyword. Please note that since static methods are processed at the time of class loading, it's all but certain that no "this" exists at the point of time, which is why its only logical the usage of this keyword isn't allowed in a static context.
On the other hand, static method can be invoked from an object because it is made accessible to the object. The intention behind static data members and behaviours is to make it common to all the instances of that class.
Keyword "this" refers to the object that you are operation with. In your case this inside any non-static methods or constructor (if you have one and and if you use "this" inside that), then "this" refers to that particular instance of the class Sub.So it is applicable only when the object is created. But anything in the static context of a class, you can use without even creating object for that as it is resolved during the class loading. "this" resolved only when object is created ( you can even say dynamically for which object). So "this" make sense in static context. Hope it helps. God bless.
when we declare variable and method is static then this is share by among object where this keyword only pointing to current object. suppose you have created five object of class foo then only one copy of made of (int y) shred by all object.so if you access int y using this keyword then compiler get a ambiguity which object have to point because static int y is shared by all object . you have access static variable using class name.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Can we override static method in Java?
We cannot override the static methods of the base class.
Actually I tried something like this:
// Base class
public class StaticExampleImpl {
protected String name="overriding";
public static void display(){
System.out.println("static method display : base class");
}
}
Then the derived class is as follows:
//derived class
public class StaticDemo extends StaticExampleImpl {
// cannot override the static methods...
//#Override
public static void display(){
System.out.println("child!!! static method display");
}
public static void main(String[] args) {
StaticDemo d=new StaticDemo();
d.display(); // derived class display is called rather than Base class.
}
}
So, when I uncomment the #Override method, it gives error as "Static methods cannot be overriden". But with commenting it works fine. So, when we create the Objects and call the static methods with the instances, those work fine. so what is the difference??
because static methods are not get inherited.
When you uncomment #Override it means you are trying to override the
static method which is not possible thats why you are getting an
error.
But when you comment //#Override it means you are declaring a new
method in child class.
Static methods does not belong to an instance of a class, it belongs to the actual class.
When you call d.display();, you are really calling the static method of the StaticDemo d reference's static method.
if you did :
StaticExampleImpl d2 = new StaticDemo();d2.display(), you will find that it calls the base class's display.
However, don't do this. It leads to confusing code, and is a bad way to implement inheritance poorly.
Overriding depends the an instance of a class. polymorphismis that you can subclass a class and the objects implementing those subclasses will have different behaviors for those method defined in the superclass (and overridden in the subclasses) .static methods does not belong to an instance of a class so the concept is not applicable.
Static methods cannot be inherited. If you want to call the 'base' class static method, you have to explicitely call StaticExampleImpl.display().
Static methods are bound to class they can't be inherited thats why you can't have base class static method in derived class.
If you are trying to override a static method, there is probably something wrong with your design.
OOP and Polymorphism allows you to do the following:
public class MyClass1 {
public String toString() { return "MyClass1 Instance"; }
}
public class MyClass2 extends MyClass1 {
#Override
public String toString() { return "MyClass1 Instance"; }
}
public void printSomething(MyClass1 myclass1){
System.out.println(myclass1);
}
Inside printSomething, the toString method which is going to be called is the one on the runtime type of myClass1: when you pass inside printSomething an instance of MyClass2, its compile-type will be MyClass1 but its runtime type will be MyClass2
It is clear that to use polymorphism you need objects instances, where the actual runtime type could different from the compile type. Static methods however do not belong to any object instance, but to the class. Why don't you explain us what you are trying to achieve?
The following code:
StaticExampleImpl one = new StaticExampleImpl();
StaticDemo two = new StaticDemo();
StaticExampleImpl three = two;
one.display();
two.display();
three.display();
Will yield the following output:
static method display : base class
child!!! static method display
static method display : base class
As you can see, the method does not get inherited. This is why they are called 'static methods': they are called statically, not dynamically, as instance methods would be. The compile-time type of the class is what matters when calling static methods, not the runtime type.
This is also why you shouldn't call static methods through object instances. Always call them like this:
StaticExampleImpl.display();
StaticDemo.display();
This completely takes away the confusion that might (will) come up when people expect inheritance to work for these methods.
any static block in java, may be static variables, methods are loaded when the class is loaded. You probably know about class loader in java. So thing is static block (methods, variables or anything is static) is loaded once. So you can’t actually override any static block.
Commenting #Override means that you are writing another static method in sub class, but not just overriding base class method.