making method final, if we really wanted to enforce this - java

i am still reading factory patterns on head first. We have an pizzaStore example and trying to localize our pizzaStore class to let franchies freedom to have their own regional style.
To do this, we changed to pizzaStore class to abstract class, and moved our factory object to "abstract createPizza(String type);" method. It is ok, i understood why.
If you look at the picture, i underlined the sentence. What it means ? " if we really want to enforce, we could make the method final ? "

The point is that subclasses are supposed to implement createPizza, but are required by contract to not override orderPizza, just call it. This policy can be enforced by making the method final.
When you design a class for inheritance, you must generally take care of all the details involved in how exactly the class is supposed to be extended.

If you make a method final classes inheriting the method cannot overwrite it. This ensures that the implementation in PizzaStore is used by all the subclasses.
Source: http://docs.oracle.com/javase/tutorial/java/IandI/final.html

Declaring a method as final, prevents the subclasses from overidding it.

If you make orderPizza method final, you cant override in your subclasses, but you can still access them. methods marked with final cant be overriden in your subclass.

Final methods cannot be overridden thus any inheriting class has the same method, they are enforced to have that same method.

This means that ChicagoStylePizzaStore is not allowed to override orderPizza().
The java final keyword: final orderPizza() enforced that the sub classes cannot overide that method.
Class Chicago then has to call orderPizza() from PizzaStorre() and not from an own method with same name.

Related

Extend interface with defined fields?

I've got a question for you? As we all know, interface fields in Java are default public, static and final as well. How about extending interfaces?
For example if we have some interface with defined fields in it and we create another interface which extends interface with fields, we shouldn't be able to inherit fields, because they are literally static and also final. But we can! So could you explain it to me why?
interface interfaceWithFields{
String name = "Matthew";}
interface interfaceWithoutFields extends interfaceWithFields{}
And when we call standard output method, it will return Matthew:
System.out.println(interfaceWithoutFields.name); //no problem at all
Thanks in advance for responses. It's late at night and I might have confused something.
This is normal. Subclasses and subinterfaces in general inherit static members from their supertypes.*
9.2:
The interface inherits, from the interfaces it extends, all members of those interfaces, except for fields, classes, and interfaces that it hides; abstract or default methods that it overrides (ยง9.4.1); and static methods.
The wording there is kind of, umm wordy, but it says interfaces inherit static fields from superinterfaces unless they are not hidden. (Hiding is when you declare a variable with the same name.)
In practice, the compiler will just replace interfaceWithoutFields.name with interfaceWithFields.name. There is only one static variable name exists.
* (Except, weirdly, static methods are not inherited from superinterfaces.)
I'm not sure if this the technical answer, but in this case it works very similar to how a normal class would work. If you inherit from a Base class with a public, static, or final field, it will also be in the extended class. So at least in that sense it seems reasonable that interfaces would in a similar manner.

Working with a superclasses private member (Java)

I have build a subclass from a class in Java that has private methods which I want to access in the subclass, I cannot change or edit the superclass. The problem is of course they are private. Suppose I have written the superclass by myself and there were certain reasons why these methods have to be private. I could copy the code in the subclass. But is there a better way (without producing so much lines of code) to get able to work with them when writing a subclass?
Ignoring that your reasons for wanting to do this are potentially very bad (there's no contract for your usage of private variables, so there are no guarantees that they won't change, or disappear completely!) you could probably do what you want using reflection:
Using:
http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#getDeclaredField(java.lang.String)
http://docs.oracle.com/javase/6/docs/api/java/lang/reflect/AccessibleObject.html#setAccessible(boolean)
http://docs.oracle.com/javase/6/docs/api/java/lang/reflect/Field.html#get(java.lang.Object)
Class c = object.getClass();
Field field = c.getDeclaredField("somePrivateInstanceVariable");
field.setAccessible(true);
Object someValue = field.get(object);
I just want to emphasise that you should consider the reasons for doing this and decide against it! If you own the code that you are extending, consider if you should instead make the field protected instead of private. Remember, hooking into code you're not supposed to have access to breaks OOP principles (you're circumventing encapsulation) and there are no guarantees the code your application depends on won't disappear in an update to the library (so you're also locking yourself down to a fixed version of the lib).
So you tried with "extends" to inherit the methods from the superclass. And of course they are private, but you can use them in the sublass. Making them abstract would force you to rewrite every in private, i see no other option.
Make super class method's protected. It would be only accessible from sub-class and package.
private modifier's are only accessible with in class.
In your case you should declare the private method as protected instead. Read this for more details on the subject.

Is there any harm in using super when not needed?

This message pertains strictly to Java. If a method is in a superclass there are two ways the method could be called:
foo();
super.foo();
Is there any harm in always doing the latter? As a coding style I prefer the latter because it's clear at a glance where the method call is coming from. Are there any circumstances where 'super' is going to be non-existent or not do what I think it would do?
I think the only harm you may have is when you want to use polymorphism so, if you call foo() and some subclass overrides foo, then the effect would be different than if you call super.foo(), basically, it depends on how you are designing the code and for what purpose.
Hope this makes it clear.
As a general rule, you should only use super.foo() inside your class foo() method. Doing otherwise, in general, goes against OOP thinking.
because it's clear at a glance where the method call is coming from
In OOP you should'n want to know where the method call "comes from". If your program (or your thinking) is depending on that, you are in potential trouble (and will probably be in actual trouble when someone decides to override the method). The method myobject.foo() must be seen from the outside as the method of the myobject's class; it should not matter if that method is implemented actually in the concrete class of its parent.
I would say there is more harm in doing the former as it's not clear that it's a method of the superclass.
Yeah this basically breaks the inheritance chain.
You don't allow the inheritance mechanism to choose what function to use even in classes derived from this one.
The point of super.foo() is to allow you to specify only when it is needed and you know no other behavior will be good.
If you do not want to explicitly avoid using an overriding method in the subclass then you should not use super.
Always using super might cause trouble if later on someone wants to override the method in the subclass.
That's a preferable way if you intend to call the method on the super class, instead of calling foo() without super.. If anyone does overwrite foo() in the subclass the super call does call the same method as before, but omiting super will now call the overwritten method. It depends on what you intent with that method call.
It depends.
If foo() is declared as final, it will make no difference at all. If foo() is not declared as final, then a subclass could override the declaration of foo() in your superclass and completely change the expected behaviour.
If you make your own class final, you can prevent it from being sub-classed, and be certain the original intent is preserved.
I would be say that this might indicate that you should think over you design again.
If you are always calling the functionality by super.foo() then you block yourself from overriding the function later, and if you don't want to have the ability to override the function, then maybe you shouldn't use inheritance as a method for accessing this functionality.
One design principle that I have heard banded about is "favour composition over inheritance", the reason for this is that your code becomes more flexible with composition rather than inheritance. And if you don't gain the positive aspects of inheritance (being able to override the function) then maybe it's wiser to not use inheritance.

How do I override a single method in java class

I am fairly new to java development and wounder how I can modify an existing Android class. I would like to change some of the methods in Notification.Builder class in Android (https://github.com/android/platform_frameworks_base/blob/master/core/java/android/app/Notification.java).
Specifically do I want to change getNotification(), but in the new implementation I need access to the private fields (e.g., mWhen, mSmallIcon).
I have tried to extend the class, but then I don't have access to the private fields of the superclass (i.e., mWhen, mSmallIcon).
What is the best practice to change the method, is it to copy the source code and modify it?
Update:
To be more precise: how can I change a single method in an existing class and still have access to the private fields of the existing class?
Thanks for all responses!
You could simply call super.getNotification() in your overriden method and modify the resulting object before returning it.
A private (inner) class, method or field are only referenced from within the class in which it is declared.
But you also can declare your own variables and work with it as you wish
The best practice is not to override methods (from third-party classes which were not designed to be overridden), but to create a new class/method which wraps the third-party class. Google for these: "fragile base class problem", "composition over inheritance".
I have tried to extend the class, but then I don't have access to the private fields of the superclass (i.e., mWhen, mSmallIcon).
In the particular class you're extending there are a limited number of methods that set the values of these fields. You can override those methods to hold onto copies of the values in new fields in your subclass which you can then use in your override of getNotification().
This is something of a hack, and wouldn't be workable with a more complex class.
Another hack is to use reflection and invoke setAccessible(true) on the field objects. This also may not be workable depending on security constraints.
If you say exactly the change you're trying to make, there might be a better way.

Should an abstract class have at least one abstract method?

Is it necessary for an abstract class to have at least one abstract method?
The subject of this post and the body ask two different questions:
Should it have at least one abstract member?
Is it necessary to have at least one abstract member?
The answer to #2 is definitively no.
The answer to #1 is subjective and a matter of style. Personally I would say yes. If your intent is to prevent a class (with no abstract methods) from being instantiated, the best way to handle this is with a privateprotected constructor, not by marking it abstract.
No, it is not necessary. You see this often back in "template method" design pattern, like HttpServlet, wherein each method already has default behaviour definied and you're free to override just one (or more) of them instead of all of them.
The HttpServlet class is merely abstract to prevent direct initialization by inadvertendly using new HttpServlet() which would otherwise basically have returned an empty, unimplemented and useless servlet instance.
In JDK 1.0 it was indeed necessary to have at least one abstract method in an abstract class. This restriction was removed in JDK 1.1 (1997? (I'm old)) and such classes added to the Java library, such as java.awt.event.KeyAdapter.
In C++ you need at least one pure virtual function to make a subclass necessary, and at least one virtual function to add RTTI to the class. Typically it makes sense to use the destructor.
Note when overriding non-abstract methods, using #Override is a good idea. It not only tells the reader important information about what the code is attempting to do, but also spots common errors where typos or incorrect parameter types prevents the override.
No - you can declare a class abstract without having any abstract methods. It may not make any sense conceptually for an instance of that class to exist, or you may want to ensure that only subclasses of that class can be instantiated (for whatever reason)
If a class has an abstract modifier on its declaration it becomes abstract class.

Categories