When are dot operators required? - java

When calling a method, I get that you have to use instanceName.method() or className.method(). However, in some cases the instanceName or className is omitted in the code and just method() is written.
Programming language is Java. Just covering this for the AP Computer Science test and I have relatively limited knowledge of coding outside of the parameters of the course so a easy to understand explanation would be greatly appreciated.
My book says something about client programs but I'm not exactly sure what it means (both in general and about client programs specifically).

I'll put my explanation as simply as possible - Usually you would use instanceName.method() when trying to effect the variables within a class. For example a "Cat" object, you could make a cat - Cat catOne = new Cat() and then use its methods catOne.setName("Kitty");. This will set this objects name to "Kitty", leaving all other cat objects with the ability to have their own unique name.
Using className.method() is done when using a static method within a class, eg public static int method(), and then using it in another class. This does not require you to instantiate an object for that class, and can use them willingly. For example, having a class called MathConstants and using something like MathConstants.getPi() ( Sorry for the crude example ).
When methods are called like methodName() , this means that the method is located within the class itself. Usually we use this , as in this.methodName(), but just using methodName() is okay.
Hope that is easy to understand

Related

Returning an Object's method names

I have the ability to run code that lets me make calculations and/or get variable information from a program. However I do not have access to the base code, and wondering if there is a way to print out all the methods an Object has available (public)?
Example the Class Shape, with sub classes of Circle and Square.
If I was able to print out methods to Circle I would possibly see:
.getRadius()
.setRadius(newValue)
but Square would have
.getSide()
.setSide(newValue)
I have a myObject, where I know I can get
myObject[1].GetLength()
myObject[1].getDimUom()
myObject[1].getQuantity().getValue()
However I am unaware of what I can set only certain things like (by trial and error)
myObject[1].setClass(newValue)
So I would like to be able to find a way to print out the method names from an Object; again without any ability to see or modify base code (like adding reflection)
What you basically want is to brake the information hiding principle which is the most fundamental principle in OOP.
What You (most likely) really want is to define a common behavior that could be implemented by the subclasses in their specific way. Regarding your example this could be a method changeSizeTo(int newValue) defined in an interface that would be implemented by your classes and each class would do something specific.
[update]
I mean anything available to public is it really hiding? – Edward
The point is not about the actual access modifiers but the question: "Does this force the caller to know what subclass this object actually is?"
Solution
You can use reflection.
Class clazz = circle.getRadius().getClass();
Method[] methods = clazz.getMethods();
for ( Method method : methods ) {
System.out.println( method.getName() );
}
With that said, you should listen to the advice given by #Timothy Truckle. You most likely have a design problem if you need to use this, assuming you aren't writing a framework or a library

How to call the template method by two names in a Template Method Pattern

I'm doing this a bit backwards because I'm following a specific sequence of project instructions. I have two java classes. One of them simulates the grep function from Linux, and the other simulates the lineCount capability. I have them both implemented, but the NEXT step in the project is to create a superclass using the template method pattern that "will contain all fields and algorithms common to the other two programs".
There is a lot of common functionality between the two, and it is apparent what parts need to be part of the template and which need to be part of the implementations. For example, each of them needs to be able to create File objects based on the path string used to call the method, and search through the File's list method using a regex that is used to call the method. This is common functionality that should definitely be part of the template/abstract class.
It would be nice to be able to declare something like this:
public abstract class RegexCommands{
protected Variables;
public Map<things> myMethod(variables){
//common functionality which includes storing and using the variables
hookMethod(); //based on what you create in commonFunctionality
return resultAfterHookMethod;
}
}
public class Grep extends RegexCommands{
public hookMethod(){
class specific things;
}
}
public class lineCount extends RegexCommands{
public hookMethod(){
class specific things;
}
}
and just call it with
RegexCommands myObject = new Grep();
myObject.myMethod(variables);
and have it return what I'm looking for (grep command for the Grep object, lineCount for the LineCount object). However, the instructions specifically state that it will be called like so:
RegexCommands myObject = new Grep();
myObject.grep(variables);
RegexCommands myObject = new LineCount();
myObject.lineCount(variables);
and also that there are slight differences in the variables used. (lineCount doesn't need a substringSelectionPattern, for example) The way I have it set up now is that the hooked methods call super to their parent, and the template calls myMethod. This is obviously not the way that it is supposed to work. For one thing, it seems like I have had to introduce non-common methods to my template that just call the main template method, which means that one could, theoretically (although I haven't tested it), do something like
RegexCommands myObject = new LineCount();
myObject.grep(variables);
Which is not behavior that I want to allow and seems like it defeats the purpose of using the template. The other problem (that I have actually run into) is that my hookMethods don't seem to have access to the instance variables created in commonFunctionality (ie when I try to access a matcher that was created in commonFunctionality, it returns null even if I declare it as an instance variable instead of a method-level scope, like I would prefer).
So I'm kind of stuck and looking for some help. How do I have these objects use the myMethod pattern in the template without this terrible workaround that destroys the separateness of my objects, and how do I have the non-common methods use ArrayLists and/or Maps from the commonFunctionality without passing EVERYTHING over as parameters (which I have been advised not to do as it ruins the point of using templates)?
For one thing, it seems like I have had to introduce non-common methods to my template that just call the main template method,
Yes you would need to introduce such methods for your given requirement. But as you stated later that this would be incorrect as a LineCount object can call a grep method, this can be avoided by doing a instance of check in the non-common methods you would be writing. Doing the job if it fits the what is expected called or exiting otherwise.
For you original problem that you have run into
my hookMethods don't seem to have access to the instance variables created in commonFunctionality (ie when I try to access a matcher that was created in commonFunctionality, it returns null even if I declare it as an instance variable instead of a method-level scope, like I would prefer).
You can't define a abstract variable in java, the only legal modifier for variable in java are
public, protected, private, static, final, transient, volatile
you need to have a concrete implementation of commonFunctionality and you can have a getter method for it. You can define a abstract method for this in the abstract class. Refer to the answer of this post for more info Abstract variables in Java?
RegexCommands myObject = new Grep();
myObject.grep(variables);
RegexCommands myObject = new LineCount();
myObject.lineCount(variables);
This is only possible (in Java) if the interface/abstract class RegexCommands defines both methods. Thus both implementation needs to implement them, too. If you want to stick to that requirement you could do that and let Grep.lineCount() throw some exception.
A workaround could be to make RegexCommands to be a facade that only delegates method calls from RegexCommands.grep() to new Grep().myObject()
However, you should contact the requestor to clarify it.

Is static late binding necessary to overload static variables?

A friend of mine asked me whether he can override a static variable in Java and I was shocked that he even thought about such a weird way of coding. Then he explained me that this is possible in PHP and I want to know whether there are a good reasons why a good developer should do that. In my opinion static members are characterized as class members and not related to an object and therefore they are not related to derivation of classes, but I cannot convince him as he is so naive and stubborn.
Can anyone give either a good argument against this whole thing or convince me that this is a cool feature?
The static inheritance does not make any sense. It is not that it is not possible, just that you get no benefit from it.
With normal inheritance you get the benefit of having a different implementation for the same thing and not knowing/caring which implementation will be used. With static inheritance you don't have an object to operate with and you are using a class name, so you cannot take advantage of polymorphism.
E.g. if you are calling Child.someMethod() you are tied to implementation of the child and if you actually just need the parent, you can just do Parent.someMethod() instead. If you need to add something to Parent implementation, you just make a Child.someOtherMethod() where you call the parent and do some other things after. The static inheritance is just syntactic sugar...
As far as I know, the static keyword in Java is used to define Class variables. A Class variable has one instance for all Objects of that class. So in Java you can not override a static variable, it doesn't make sense. Any changes done to a static variable in one Class propagates to another class. This is what static is used for, in JAVA.
This is the same way IT SHOULD WORK in PHP (I am not really a PHP expert), but if your friend can provide code showing that a static variable in PHP was overridden and the variable has a different value that from another class, I will be very glad.

Using a function in two unrelated Java classes

I have two classes in my Java project that are not 'related' to each other (one inherits from Thread, and one is a custom object. However, they both need to use the same function, which takes two String arguments and does soem file writing stuff. Where do I best put this function? Code duplication is ugly, but I also wouldn't want to create a whole new class just for this one function.
I have the feeling I am missing a very obvious way to do this here, but I can't think of an easy way.
[a function], which takes two String arguments and does soem file writing stuff
As others have suggested, you can place that function in a separate class, which both your existing classes could then access. Others have suggested calling the class Utility or something similar. I recommend not naming the class in that manner. My objections are twofold.
One would expect that all the code in your program was useful. That is, it had utility, so such a name conveys no information about the class.
It might be argued that Utility is a suitable name because the class is utilized by others. But in that case the name describes how the class is used, not what it does. Classes should be named by what they do, rather than how they are used, because how they are used can change without what they do changing. Consider that Java has a string class, which can be used to hold a name, a description or a text fragment. The class does things with a "string of characters"; it might or might not be used for a name, so string was a good name for it, but name was not.
So I'd suggest a different name for that class. Something that describes the kind of manipulation it does to the file, or describes the format of the file.
Create a Utility class and put all common utility methods in it.
Sounds like an ideal candidate for a FileUtils class that only has static functions. Take a look at SwingUtilities to see what I'm talking about.
You could make the function static in just one of the classes and then reference the static method in the other, assuming there aren't variables being used that require the object to have been instantiated already.
Alternatively, create another class to store all your static methods like that.
To answer the first part of your question - To the best of my knowledge it is impossible to have a function standalone in java; ergo - the function must go into a class.
The second part is more fun - A utility class is a good idea. A better idea may be to expand on what KitsuneYMG wrote; Let your class take responsibility for it's own reading/writing. Then delegate the read/write operation to the utility class. This allows your read/write to be manipulated independently of the rest of the file operations.
Just my 2c (+:

Java abstract static Workaround

I understand that neither a abstract class nor an interface can contain a method that is both abstract and static because of ambiguity problems, but is there a workaround?
I want to have either an abstract class or an interface that mandates the inclusion of a static method in all of the classes that extend/implement this class/interface. Is there a way to do this in Java? If not, this may be my final straw with Java...
EDIT 1: The context of this problem is that I have a bunch of classes, call them Stick, Ball, and Toy for now, that have a bunch of entries in a database. I want to create a superclass/interface called Fetchable that requires a static method getFetchables() in each of the classes below it. The reason the methods in Stick, Ball, and Toy have to be static is because they will be talking to a database to retrieve all of the entries in the database for each class.
EDIT 2: To those who say you cannot do this in any language, that is not true. You can certainly do this in Ruby where class methods are inherited. This is not a case of someone not getting OO, this is a case of missing functionality in the Java language. You can try to argue that you should never need to inherit static (class) methods, but that is utterly wrong and I will ignore any answers that make such points.
You have a couple of options:
Use reflection to see if the method exists and then call it.
Create an annotation for the static method named something like #GetAllWidgetsMethod.
As others have said, try to not use a static method.
There are lots of answers about 'this does'nt make sense..' but indeed I met a similar problem just yesterday.
I wanted to use inheritance with my unit tests. I have an API and several its implementations. So I need only 1 set of unit tests for all implementations but with different setUp methods which are static.
Workaround: all tests are abstract classes, with some static fields with protected access modifier. In all implementations I added static methods which set these static fields. It works rather nice, and I avoided copy and paste.
I too am dealing with this problem. For those that insist that it "doesn't make sense", I would invite you to think outside of that semantic box for a moment. The program I am working with is inherently about reflection.
Reflection, as you know, can take three orders of magnitude longer than straight-up binary function calling. That is an inevitable problem, and the software needs to port to as many machines as possible, some of which will be 32 bit and slower than my development machine to begin with. Thus, the applicability of a class to the requested operation needs to be checked via a static method, and all of the reflective methods are run at once during module booting.
Everything works, first and foremost. I've built the entire thing. The only catch is that a module can be compiled in a .class without compile time checking to see if the identifying static function exists at all, resulting in an innately useless class. Without the identifier, and its included information, for security's sake the module is not loaded.
I clearly understand the issue with the complete definition of "abstract" and "static", and understand that they don't make sense together. However, the ability to have a class method that is compiler-enforced for inclusion is lacking in Java, and as much as I like the language, I miss it. Thus, this is a human constraint on every programmer that ever works on the software, which I'm sure we can all agree is a pain.
There's a lot of 'this makes no sense' or 'this can't be because' and 'why do you want it?' (or worse: 'you don't have to want it!') in all those answers. However, these answers also indirectly give reasons why it should be possible.
It must be differentiated between the concept and the implementation.
Sure, overriding a static method makes no sense. And it also isn't what the question was about.
It was asked for a way to force implementation of a certain static method (or constant or whatever) in every derived class of an abstract class. Why this is required it the matter of the one who wants to write an appllication with Jave, and no business of anyone else.
This has nothing to do with how the compiler compiles the method and how it is done at runtime.
Why shoudl it be possible? because there are things that are class specific (and not instance specific) and therefore should be static, while they NEED to be impleented in every single subclass (or class that implements an interface).
Let's say there is an abstract class 'Being'. Now there are subclasses like 'animals' and 'plants'.
Now there are only mammals and fishes allowed for animals. This information is specific to the animals class, not to any instance nor doe sit belong to any superclass or subclass. However, this information must be provided by teh class, not an instance, because it is required to properly construct an animal instance. So it MUST be there and it CANNOT be in the instance.
In fact, Java has such a thing- Every object has a class specific field 'class'. It is class-specific, not inherited, no override and it must be there. Well the compiler creates it implicitly, but obviously the compiler CAN do it. So why not allowing this for own fields too.
After all, it is just a matter of definition how the combination 'abstract static' is interpreted when the compiler checks the intheritance chain for abstract functions.
Nobody was ever demanding that there should be an inheritance of the superclass class functions (which could still make some sense, depending on what this function actually does - after all classes inherit static functions of their superclasses, even though you might get a warning that you should access it directly when you call it by the subclass))
But to summarize: the Java language offers no way to do it at compile time while there is no reason (othe rthan plain dogmatic) to not doing so.
The only way is to write a static final function to the abstract class that tries to find the static function/field of the subclass when it is loaded (or loads all existing subclasses and checks them). If properly made, it gives a runtime error on first use. Complex and dirty but better than nothing. At least it prevents bugs where you get the information from the wrong superclass.
It won't work for interfaces, though.
A type system allows you to express some constraints among types, but it's limited. That's why javadocs are littered with constraints in human language, asking people to follow rules that the compiler cannot check.
if you want to extend it beyond what language provides natively, you can write your own static analysis tool. that is not uncommon. for example: findbug. also IDEs do that too, they checking thing beyond what language dictates. you can write a plug in to enforce that a subclass must have a static method of such signature.
in your case, it's not worth it. have javadoc in the superclass urge implementors to include a static method, that's good enough.
I'll provide a convoluted way of expressing your constraint anyway, but DO NO DO IT. people get really carried away of make everything checkable at compile time, at the price of making code unreadable.
interface WidgetEnumerator
{
List getAllWidgets();
}
public class Abs<T extends WidgetEnumerator>
{
static List getAllWidgets(Class<? extends Abs> clazz){ ... }
}
public class Sub extends Abs<SubWidgetEnumerator>
{
}
public class SubWidgetEnumerator implements WidgetEnumerator
{
public List getAllWidgets() { ... }
}
How it works: for any subclass of Abs, it is forced to provide an implementation of WidgetEnumerator. subclass author cannot forget that. Now invocation Abs.getAllWidgets(Sub.class) contains sufficient information to resolve that implementation, i.e. SubWidgetEnumerator. It is done through reflection, but it is type safe, there are no string literals involved.
I think I can give you a better answer after seeing your edits--your best bet is probably a factory pattern. (Not lovely, but better than singleton).
abstract class Widget
public static Widget[] getAllWidgetsOfType(Class widgetType) {
if(widgetType instanceof ...)
}
class Ball extends Widget
class Stick extends Widget
class Toy extends Widget
This is not a very good way to do it, but it's typical. Hibernate is the tool you would normally use to solve this problem, this is exactly what it's designed for.
The big problem is that it requires editing the base class whenever you add a new class of a given type. This can't be gotten around without reflection. If you want to use reflection, then you can implement it this way (Psuedocode, I'm not going to look up the exact syntax for the reflection, but it's not much more complex than this):
public static Widget[] getAllWidgetsOfType(Class widgetType) {
Method staticMethod=widgetType.getStaticMethod("getAllInstances");
return staticMethod.invoke();
}
This would give the solution you were asking for (to be bothered by the need to modify the base class each time you add a child class is a good instinct).
You could also make it an instance method instead of a static. It's not necessary, but you could then prototype the method (abstract) in Widget.
Again, all this is unnecessary and sloppy compared to Hibernate...
Edit: If you passed in a live "Empty" instance of a ball, stick or toy instead of it's "Class" object, you could then just call an inherited method and not use reflection at all. This would also work but you have to expand the definition of a Widget to include an "Empty" instance used as a key.
Static methods are relevant to an entire class of object, not the individual instances. Allowing a static method to be overridden breaks this dictum.
The first thing I would consider is to access your database from a non-static context. This is actually the norm for Java apps.
If you absolutely must use a static method, then have it parameterised with instance specific arguments (of a generic type) to allow the different subclasses to interact with it. Then call that single static method from you polymorphic methods.
No. You can't do that. If you're willing to compromise and make the method non-static or provide an implementation of the static method in your abstract class, you'll be able to code this in Java.
Is there a way to do this in Java?
I don't think there is a way to do this in any language. There's no point to it, since static methods belong to a class and can't be called polymorphically. And enabling polymorphic calls is the only reason for interfaces and abstract classes to exist.
Create a context interface containing your method with a name that matches your problem domain. (Name it "World" if you absolutely have to, but most of the time there's a better name)
Pass around implementation instances of the context object.
Ok, maybe my question was poorly asked, it seems like most of you didn't get what I was trying to do. Nonetheless, I have a solution that is somewhat satisfactory.
In the abstract super class, I am going to have a static method getAllWidgets(Class type). In it I'll check the class you passed it and do the correct fetching based on that. Generally I like to avoid passing around classes and using switches on stuff like this, but I'll make an exception here.
static methods can't be abstract because they aren't virtual. Therefore anywhere that calls them has to have the concrete type with the implementation. If you want to enforce that all implementations of an interface have a certain static method, then that suggests a unit test is required.
abstract class A
{
public static void foo()
{
java.lang.System.out.println("A::foo");
}
public void bar()
{
java.lang.System.out.println("A::bar");
}
}
class B extends A
{
public static void foo()
{
java.lang.System.out.println("B::foo");
}
public void bar()
{
java.lang.System.out.println("B::bar");
}
}
public class Main
{
public static void main(String[] args)
{
B b = new B();
b.foo();
b.bar();
A a = b;
a.foo();
a.bar();
}
}
For what it is worth I know exactly what you are trying to do.
I found this article while searching for the reasons I can't do it either.
In my case I have HUNDREDS of classes that inherit from a central base base and I want simply to get a reference like this:
ValueImSearchingFor visf = StaticClass.someArbitraryValue()
I do NOT want to write/maintain someArbitraryValue() for each and every one of hundreds of the inherited classes -- I just want to write logic once and have it calc a Unique Class-Sepcific value for each and every future written class WITHOUT touching the base class.
Yes I completely get OO - I've been writing Java for about as long as it's been available.
These specific classes are more like "Definitions" as opposed to actual Objects and I don't want to instantiate one every time I just need to see what someArbitraryValue() actually is.
Think of it as a PUBLIC STATIC FINAL that allows you to run a Method ONCE to set it initially. (Kinda like you can do when you define an Enum actually...)
I'd make a WidgetCollection class with an abstract Widget inner class.
You can extend the WidgetCollection.Widget class for each of your types of Widget.
No static methods necessary.
Example (not compiled or tested):
class WidgetCollection<W extends Widget> {
Set<W> widgets = new HashSet<W>();
Set<W> getAll() {
return widgets;
}
abstract class Widget {
Widget() {
widgets.add(this);
}
abstract String getName();
}
public static void main(String[] args) {
WidgetCollection<AWidget> aWidgets = new WidgetCollection<AWidget>();
a.new AWidget();
Set<AWidget> widgets = aWidgets.getAll();
}
}
class AWidget extends Widget {
String getName() {
return "AWidget";
}
}
It doesn't make sense to do what you're asking:
Why can't static methods be abstract in Java

Categories

Resources