Related
I'm writing an explanation for some code for a course, and have been accidentally using the words method and function interchangeably. I decided to go back over and fix the wording, but ran into a hole in my understanding.
From what I understand, a subroutine is a function if it doesn't act on an instance of a class (its effect is restricted to its explicit input/output), and is a method if it operates on an instance of a class (it may carry out side effects on the instance that make it impure).
There's a good discussion here on the topic. Note that by the accepted answer's definitions, a static method should actually be a function because an instance is never implicitly passed, and it doesn't have access to any instance's members.
With this is mind though, shouldn't static methods actually be functions?
By their definition they don't act on particular instances of a class; they're only "tied" to the class because of relation. I've seen a few good looking sites that refer to static subroutines as "methods" though (Oracle, Fredosaurus, ProgrammingSimplified), so either they're all overlooking the terminology, or I'm missing something (my guess is the latter).
I'd like to make sure I am using the correct wording.
Can anybody clear this up?
This quote from 8.4.3.2 may help:
A method that is declared static is called a class method.
A method that is not declared static is called an instance method [...].
Class methods: associated with a class.
Instance methods: associated with an instance.
Java just wants you to "think object-oriented". Also, static methods have access to a surrounding scope which may include state. In a way, the class is like an object itself.
The simple answer is that when Java decided to call everything a "method", they didn't care about the distinction between a function and a method in theoretical computer science.
Static methods are not exactly functions, the difference is subtle, but important.
A static method using only given input parameters is essentially a function.
But static methods may access static variables and other static functions (also using static variables) so static methods may have a state which is fundamentally different to a function which are by definition stateless.
(ADDENDUM: While programmers are often not so strict with using "function" as definition, a strict function in computer science can access only input parameters). So defining this case of accessing static fields it is not valid to say that static methods are always functions.
Another difference which justifies the usage of "static method" is that you can define in C derivates global functions and global variables which can be accessed everywhere. If you cannot access the class which contain static methods, the methods are inaccessible, too. So "static methods" are limited in their scope by design in contrast to global functions.
In Java, a user-defined class is actually an instance of a subclass of java.lang.Class.
In this sense, static methods are attached to an instance of a conceptual class: they are attached to an instance of a subclass of java.lang.Class.
With this in mind, the term "class method" (an alternate name for Java's static methods) begins to make sense. And the term "class method" can be found in many places: Objective C, Smalltalk, and the JLS -- to name just a few.
In computer science function clearly maps to a static method. But "method" of a class is a bit generic, like "member" (field member, method member). There are wordings like
Data members and method members have two separate name spaces: .x and .x() can coexist.
So the reason is, that as the philosoph Ludwig Wittgenstein said, Language is a tool with different contexts. "Method" is a nice moniker in the citation above to categorize a "member".
Your thinking is right and it makes sense. It's just not established terminology in the Java community. Let me explain some internals that can help understand why the terminology subsists.
Java is a class based object oriented language. A method is always member of a class or instance (This is a general statement valid for other programming languages too). We think of class and instance being both objects.
Instance method (dynamic)
You cannot invoke this method from a class directly, you have to create an instance. Each instance references that method. You can overwrite a method definition with the exact same method signature (when subclassing), i.e. the reference points to a different method (which has the same signature, but can have a different method body). The method is dynamic.
Class method (static)
You only can invoke this method from the class directly, i.e. you don't need to create an instance of that class. There is only one global definition of that method in the whole program. You cannot overwrite the exact same method signature when the method is declared static, because there is only one definition valid for the whole program. Note that the method is member of the class object itself, the instances have all the same unique (and fix) reference to that method.
Here is another take on the terminology, using Scala as a mnemonic:
In Scala you have objects, which are singleton instances of an implicitly defined class 1.
Per your definition, we can call these subroutines belonging to the object methods, as they operate on a single instance of the class.
Additionally the object will also define class A, and create all of the methods in object A as static methods on class A (for interfacing with Java) [2].
Therefore we can say that the static methods of Java class A access the same members as the Scala singleton instance, which per your definition then deserve to be called (static) methods of class A.
Of course, the main difference is - method can use static fields, not only method parameters.
But there is additional one - polymorphism!
Results of evaluation Class A.doTheSameStaticMethod() and ClassB.doTheSameStaticMehod() will be depends of class. In this case function is impotent.
Each class has an object to represent it that is an instance of a subclass of the Class class. Static methods are really instance methods on these objects that are instances of a subclass of Class. They have access to state in the form of static fields, so they are not restricted to being just (stateless) functions. They are methods.
We know 'interface' in java provide a common way to access objects who implementing it, but i wonder if there's a way like interface which not just for accessing the object's method, but also for accessing the class's method(static method). I want to use it to invoke an array of different classes's static factory method. Does java provide something like it?
No.
But you can implement the pattern you describe easily with an ordinary object interface, then a set of classes that just wrap the static methods you wish to call through to.
If your intentions is to call static method of an implementing class using Interface reference, the answer is No. static members belong to class only, so you will always need a Class type reference (actually it should be the class name) to access them.
With interfaces you can only point to what you have declared in it.
No, there's no kind of "interface for static methods" in Java.
(Aside from anything else, how would you expect to specify the class in question? Even generics wouldn't help here due to type erasure.)
This question already has answers here:
Why is method overloading and overriding needed in java? [duplicate]
(2 answers)
Closed 8 years ago.
Recently I was asked this question "why should one override a method? "
I replied, if I have a class with 10 methods and I want to use all of its functionality except one method, then I will override that method to have my own functionality.
Then the interviewer replied in that case why cant we write a new method with a different name and use that method instead.
Yes this is also right. Now I am confused. What is the real objective in overriding a method?
Can anyone please tell me? Thank you all in advance.
If you will give another name to the method in derived class, you cant invoke it with same interface. You can always invoke it through base class pointer.
i.e.
Base p = new Derived();
p.overrideMethod();
If Derived class is derived from Base then it will automatically call the derived version and not of Base. In case of different name, it is not possible. It is called code against interfaces and not implementations.
.
why cant we write a new method with a different name and use that method instead
It is because we want to use polymorphism. You could tell the interviewer this example: There is a module that calls specific methods on objects you give it; now imagine you can't change that module (e.g. no source). You can't tell it to use a different method but you can give it an object of a subclass which has overridden that method. To the module it will appear that nothing changed.
In practice it is also often the case that you could change that module but dont want to.
I replied, if I have a class with 10 methods and I want to use all of
its functionality except one method, then I will override that method
to have my own functionality.
=> Very often a way to break the Liskov Substitution principle ... => very bad OO design
You have many examples on the web of this "break" but a you can find a good explanation here.
The benefit of overriding is: ability to define a behavior that's specific to the subclass type which means a subclass can implement a parent class method based on its requirement.
One uses interfaces to allow for multiple implementations and one uses overriding to simplify the implementation of an interface (e.g. when implementing a WindowListener, one typically extends and overrides a method of WindowAdapter so that one does not need to provide definitions for the cases where the default behavior is sufficient). Adding a new method rather than overriding would not work in this case, because the caller understands the interface and invokes its methods; the whole point of overriding here is to change the behavior for the calls to the interface. If you simply added a new function, then the caller would have to know about it, which defeats the entire isolation between the consumer of a piece of functionality and the provider of that functionality which is what interfaces are intended to provide.
Overriding is a feature that is available while using Inheritance.
It is used when a class that extends from another class wants to use most of the feature of the parent class and wants to implement specific functionality in certain cases.
In such cases we can create methods with the same name and signature as in the parent class. This way the new method masks the parent method and would get invoked by default.
The main objective of overriding is code reuseablity which can be advatageous in big projects,it also provide flexiblity means you can pass different sets of input from any class and get the output
Following a tutorial on the internet regarding Soap development with Java, I found this link, with a rather unusual code for myself.
The code:
public class SoapService extends Object {
/** Creates new SoapService */
public SoapService() {
}
/** This is the SOAP exposes method
*/
public String sayGreeting(String name)
{
return "Hello "+name;
}
}
What's with the 'extends Object' syntax ? I've never encountered this kind of syntax (only on Generics).
Does this syntax has any purpose or is 'plain dumb' ?
Unless the Object class is not actually the java.lang.Object class (the tutorial does not include the imports, so it's hard to see), the extends Object is redundant.
All objects in Java implicitly extend Object, so I'd say it's redundant.
All classes extend Object implicitly anyway so it's just redundant coding having no impact.
Looks a bit like generated code - it's extra effort for a source code generator to omit the "extends" clause if it is not needed, especially if the generator is template-based.
It just means it inherits directly from the Object class. Here is more about inheritance in Java.
No. It's just explicitly doing something that is implicit.
It's unneeded. Every class in Java extends Object at some level. Leave it out, unless you need to clarify something specific.
Extends clause is optional as stated in Java Language Specification. If it is omitted, the class is derived from java.lang.Object. It is just a matter of coding style to write it or not to write it in this case. Usually it is omitted.
It is silly code. Every class in Java extends an Object class. No need to type this explisitly
There is one possibility and that is the person who made it don't want you to extend any classes. You can always do a workaround of course but that is the only thing I can come up with that makes sense.
I think it's redundant.
In Junit source code:
public class TestFailure extends Object {}
I don't know why this class extends Object.
My vote, plain dumb - but then I only play with Java...
But any class inherits from the Object Class as far as I know...
It is legal but useless boilerplate. Everything extends Object so the language spec allows you to leave it out, and it generally should be left out (some writers of coding standards disagree).
The situation is the same in generics (extends Object is implicit and redundant), it is just that for some reason (I have seen some claim early buggy Generics implementations had issues with the ? wildcard) it has caught on a bit more there.
As a matter of fact, it does not seem to be simply redundant, especially when working in the JWS webservices environment.
When defining a class for an XML type to be transported over SOAP, I use the wsimport tool to fetch client dependencies from the WSDL, which creates package-local copies of these classes. By explicitly extending Object, one can seamlessly cast between the classes from the two distinct packages.
Not doing so leads to a compilation error when trying to use a class method from package A that expects an argument type of the class in in package A, and passing in an object generated from the equivalent class in package B.
As java is an object oriented language, it supports inheritance which inherits the properties of the another class, for example all java objects inherits from java.lang.Object class.From the above example it is understood that it is the explanation of inheritance. Note that all classes, whether they state so or not, will be inherit from java.lang.Object.
Any class that doesn't explicitly extend another class,implicitly extends Object
all classes extends the java.lang.Object by default. You can see it
here
Why not make it explicit?
I'm for adding it in - not everyone "implicitly" knows that every Java class implicitly extends Object. By writing it explicitly they don't have to guess.
This question already has answers here:
implicit super-interface in Java?
(4 answers)
Closed 4 years ago.
I'm working through some homework and a question on a previous exam paper asks to name all of the abstract classes in a given UML diagram. Fairly straightforward, I suppose. There are one abstract class and three interfaces. Do these interfaces qualify as abstract classes, in general?
Thing is, while technically interfaces may be represented as classes in languages like Java, I wouldn't consider them classes.
Abstract? Hell yes. Class? No.
Interfaces cannot have constructors, neither properties, fields, function bodies, etc. Interfaces cannot be inherited, they are implemented (again, technically it might be true that implementing an interface is actually inheriting it in specific languages, but that's not my point.) Interfaces are more like 'contracts' as they do not define any behaviour whatsoever like classes.
Now if this is a homework then you shouldn't really argue about these sort of stuff with the teacher. Just check your lecture notes and see if the word "class" is mentioned anywhere in the your teacher's definition of interface.
All interface are indeed abstract
Actually, you can declare an method as abstract within an interface... except any 'checkstyle' tool will tell you the abstract keyword is redundant. And all methods are public.
If a class implements an interface and does not implement all its methods, it must be marked as abstract. If a class is abstract, one of its subclasses is expected to implement its unimplemented methods.
To echo other answers, an interface is not a class.
An interface is a reference type, similar to a class, that can contain only constants, method signatures, and nested types. There are no method bodies. Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces.
Interfaces are not part of the class hierarchy, although they work in combination with classes.
When you define a new interface, you are defining a new reference data type. You can use interface names anywhere you can use any other data type name. If you define a reference variable whose type is an interface, any object you assign to it must be an instance of a class that implements the interface
To better explain why an interface is not a class, consider the following:
1/ an interface is a type used by values
2/ a class is for Objects
3/:
Object a = new Date();
String s = a.toString();
The type of the variable 'a' is Object (which is actually a type notation in Java source code meaning a reference to an Object),
but the class of the object it points to is Date.
The type (Object) only affects what code is valid according to the compiler's type-checking, but not what the code actually does.
The class of the object affects what the code does, so that the a.toString() call in the second line returns a String that looks like a Date, not one that looks like "java.lang.Object#XXXXXXXX".
Since an Interface is a type, it is used for values only, and will not represent what objects will actually do in term of runtime.
In Java though, theres a twist to the tale - all Interfaces in Java extend java.lang.Object! Try adding a method:
public void notify();
in an interface and see what happens..
An Interface extending a Class - Does that make the Interface a Class? Or the Class an Interface?? Uhh-huh.. Guess it was a hack that had to be done to prevent interfaces overriding the definitions in java.lang.Object that implementations of the interface had to extend anyway.
You've only asked about the abstract side, but don't forget the class side - I wouldn't call an interface a class, so even though interfaces are abstract (as per the specification), I still don't think they count as abstract classes. It may be worth explicitly explaining that though :)
Yes, an Interface is implicitly Abstract. Look behind the scenes as to the way it is encoded to a .class file.
Semantics are a funny thing though; under exam conditions "abstract class" would have to literally be compiled from a .java source file using abstract class in the Class' declaration.
An interface contains prototype of methods (i.e Declaration ) not defination but Abstract class can contain defination of method & atleast one Abstract method (method with only prototype)
Interfaces are used to break the Object Inheritance.
They could hold two or more objects of several classes
and classes hierarchies.
Look at an interface as an outlet plug. All classes
implementing an Interface need to have one, the same
way a computer, a coffee machine, a ventilator and a
refrigerator need to have the same device to get
power.
Abstract class looks like interface. Abstract classes can have implementations where as interface can't have any implementations.
Then, there is a question. Can we call abstract class as interface if they only have method signatures?
I think, abstract classes, unlike interfaces, are classes. They are expensive to use because there is a lookup to do when you inherit a class from abstract class.