Change the access modifier of an overridden method in Java? - java

Is there a reason one can change the access modifier of an overridden method? For instance,
abstract class Foo{
void start(){...}
}
And then change the package-private access modifier to public,
final class Bar extends Foo{
#Override
public void start(){...}
}
I'm just asking this question out of curiosity.

Java doesn't let you make the access modifier more restrictive, because that would violate the rule that a subclass instance should be useable in place of a superclass instance. But when it comes to making the access less restrictive... well, perhaps the superclass was written by a different person, and they didn't anticipate the way you want to use their class.
The programs people write and the situations which arise when programming are so varied, that it's better for language designers not to "second-guess" what programmers might want to do with their language. If there is no good reason why a programmer should not be able to make access specifiers less restrictive in a subclass (for example), then it's better to leave that decision to the programmer. They know the specifics of their individual situation, but the language designer does not. So I think this was a good call by the designers of Java.

Extending a class means the subclass should at least offer the same functionality to the other classes.
If he extends that, then it is not a problem.
Extending could be be either adding new methods or by offering existing methods to more classes like making a package-access method public.

There is only one, you might want the override to be visible by more classes, since no modifier is default, public broadens that.

The explaination is this:-
It's a fundamental principle in OOP: the child class is a fully-fledged instance of the >parent class, and must therefore present at least the same interface as the parent class. >Making protected/public things less visible would violate this idea; you could make child >classes unusable as instances of the parent class.
class Person{
public void display(){
//some operation
}
}
class Employee extends Person{
private void display(){
//some operation
}
Person p=new Employee();
Here p is the object reference with type Person(super class),when we are calling >p.display() as the access modifier is more restrictive the object
reference p cannot access child object of type Employee

Edit: OK, I changed my answer to fix the problem.
If that couldn't be done, then there would be some cases where a class wouldn't be able to implement an iterface and extend a class because they have the same method with different access modifiers.
public Interface A {
public void method();
}
public abstract classs B {
protected void method();
}
public class AB extends B implements A {
/*
* This would't be possible if the access modifier coulnd't be changed
* to less restrictive
*/
public void method();
}

Related

Difference between Interface declared in Class and Interface declared as a file [duplicate]

I have just found a static nested interface in our code-base.
class Foo {
public static interface Bar {
/* snip */
}
/* snip */
}
I have never seen this before. The original developer is out of reach. Therefore I have to ask SO:
What are the semantics behind a static interface? What would change, if I remove the static? Why would anyone do this?
The static keyword in the above example is redundant (a nested interface is automatically "static") and can be removed with no effect on semantics; I would recommend it be removed. The same goes for "public" on interface methods and "public final" on interface fields - the modifiers are redundant and just add clutter to the source code.
Either way, the developer is simply declaring an interface named Foo.Bar. There is no further association with the enclosing class, except that code which cannot access Foo will not be able to access Foo.Bar either. (From source code - bytecode or reflection can access Foo.Bar even if Foo is package-private!)
It is acceptable style to create a nested interface this way if you expect it to be used only from the outer class, so that you do not create a new top-level name. For example:
public class Foo {
public interface Bar {
void callback();
}
public static void registerCallback(Bar bar) {...}
}
// ...elsewhere...
Foo.registerCallback(new Foo.Bar() {
public void callback() {...}
});
The question has been answered, but one good reason to use a nested interface is if its function is directly related to the class it is in. A good example of this is a Listener. If you had a class Foo and you wanted other classes to be able to listen for events on it, you could declare an interface named FooListener, which is ok, but it would probably be more clear to declare a nested interface and have those other classes implement Foo.Listener (a nested class Foo.Event isn't bad along with this).
Member interfaces are implicitly static. The static modifier in your example can be removed without changing the semantics of the code. See also the the Java Language Specification 8.5.1. Static Member Type Declarations
An inner interface has to be static in order to be accessed. The interface isn't associated with instances of the class, but with the class itself, so it would be accessed with Foo.Bar, like so:
public class Baz implements Foo.Bar {
...
}
In most ways, this isn't different from a static inner class.
Jesse's answer is close, but I think that there is a better code to demonstrate why an inner interface may be useful. Look at the code below before you read on. Can you find why the inner interface is useful? The answer is that class DoSomethingAlready can be instantiated with any class that implements A and C; not just the concrete class Zoo. Of course, this can be achieved even if AC is not inner, but imagine concatenating longer names (not just A and C), and doing this for other combinations (say, A and B, C and B, etc.) and you easily see how things go out of control. Not to mention that people reviewing your source tree will be overwhelmed by interfaces that are meaningful only in one class.So to summarize, an inner interface enables the construction of custom types and improves their encapsulation.
class ConcreteA implements A {
:
}
class ConcreteB implements B {
:
}
class ConcreteC implements C {
:
}
class Zoo implements A, C {
:
}
class DoSomethingAlready {
interface AC extends A, C { }
private final AC ac;
DoSomethingAlready(AC ac) {
this.ac = ac;
}
}
To answer your question very directly, look at Map.Entry.
Map.Entry
also this may be useful
Static Nested Inerfaces blog Entry
Typically I see static inner classes. Static inner classes cannot reference the containing classes wherease non-static classes can. Unless you're running into some package collisions (there already is an interface called Bar in the same package as Foo) I think I'd make it it's own file. It could also be a design decision to enforce the logical connection between Foo and Bar. Perhaps the author intended Bar to only be used with Foo (though a static inner interface won't enforce this, just a logical connection)
If you will change class Foo into interface Foo the "public" keyword in the above example will be also redundant as well because
interface defined inside another interface will implicitly public
static.
In 1998, Philip Wadler suggested a difference between static interfaces and non-static interfaces.
So far as I can see, the only difference in making an
interface non-static is that it can now include non-static inner
classes; so the change would not render invalid any existing Java
programs.
For example, he proposed a solution to the Expression Problem, which is the mismatch between expression as "how much can your language express" on the one hand and expression as "the terms you are trying to represent in your language" on the other hand.
An example of the difference between static and non-static nested interfaces can be seen in his sample code:
// This code does NOT compile
class LangF<This extends LangF<This>> {
interface Visitor<R> {
public R forNum(int n);
}
interface Exp {
// since Exp is non-static, it can refer to the type bound to This
public <R> R visit(This.Visitor<R> v);
}
}
His suggestion never made it in Java 1.5.0. Hence, all other answers are correct: there is no difference to static and non-static nested interfaces.
In Java, the static interface/class allows the interface/class to be used like a top-level class, that is, it can be declared by other classes. So, you can do:
class Bob
{
void FuncA ()
{
Foo.Bar foobar;
}
}
Without the static, the above would fail to compile. The advantage to this is that you don't need a new source file just to declare the interface. It also visually associates the interface Bar to the class Foo since you have to write Foo.Bar and implies that the Foo class does something with instances of Foo.Bar.
A description of class types in Java.
Static means that any class part of the package(project) can acces it without using a pointer. This can be usefull or hindering depending on the situation.
The perfect example of the usefullnes of "static" methods is the Math class. All methods in Math are static. This means you don't have to go out of your way, make a new instance, declare variables and store them in even more variables, you can just enter your data and get a result.
Static isn't always that usefull. If you're doing case-comparison for instance, you might want to store data in several different ways. You can't create three static methods with identical signatures. You need 3 different instances, non-static, and then you can and compare, caus if it's static, the data won't change along with the input.
Static methods are good for one-time returns and quick calculations or easy obtained data.

Why you cannot declare member interfaces in a local class?

You cannot declare an interface inside a block like below
public void greetInEnglish() {
interface HelloThere {
public void greet();
}
class EnglishHelloThere implements HelloThere {
public void greet() {
System.out.println("Hello " + name);
}
}
HelloThere myGreeting = new EnglishHelloThere();
myGreeting.greet();
}
In This Oracle tutorial I got "You cannot declare member interfaces in a local class." because "interfaces are inherently static."
I am eagar to understand this with more rational information, why and how interface are inherently static?
and why above code does not make sense?
Thanks in advance to elloborate!
I am eagar to understand this with more rational information, why and
how interface are inherently static?
because interfaces are implicitly static, and you can't have non-final statics in an inner class.
Why are they implicitly static?
because that's the way they designed it.
and why above code does not make sense?
because of the above reason ,
Now lets make it simple :
What static means - "not related to a particular instance". So, suppose, a static field of class Foo is a field that does not belong to any Foo instance, but rather belongs to the Foo class itself.
Now think about what an interface is - it's a contract, a list of methods that classes which implement it promise to provide. Another way of thinking about this is that an interface is a set of methods that is "not related to a particular class" - any class can implement it, as long as it provides those methods.
So, if an interface is not related to any particular class, clearly one could not be related to an instance of a class - right?
I also suggest you to study Why static can't be local in Java?
Any implementations can change value of fields if they are not defined as final. Then they would become a part of the implementation.An interface is a pure specification without any implementation.
If they are static, then they belong to the interface, and not the object, nor the run-time type of the object.
An interface provide a way for the client to interact with the object. If variables were not public, the clients would not have access to them.
Your code does not make sense because you define the interface within the body of a method. You can define an interface either at top level or in another class or interface.
You cannot declare an interface inside a block
reference

java - unique difference between abstract class and concrete class

I know few differences between abstract class and concrete class. I know that you can't create an instance with abstract class unlike concrete class, abstract class can have 'abstract' methods.
But i have an example like the following. A lot of times, we see the following examples at work. I will just skip some common methods that can be defined in the Parent class.
public abstract class Parent {
public void init() {
doInit();
}
public abstract void doInit();
}
public class Child extends Parent {
public void doInit() {
// implementation
}
}
I think that we can do the same thing with a concrete class like the following.
public class Parent {
public void init() {
doInit();
}
public void doInit() {
// Empty
}
}
I am curious to see if there is any unique situation that we have to use abstract class. Is there any significant difference during runtime with the above example?
Thank you.
The reason to use abstract class in this situation is to force everyone inheriting your base class to override the abstract doInit method. Without the class and the method being abstract, they may forget to do so, and the compiler would not catch them.
In addition to this pragmatic purpose, abstract classes provide a powerful way to communicate your design idea to the readers of your code. An abstract class tells the reader that the methods inside provide some common implementation for a group of related classes, rather than implementing a single concept that you are modeling. Very often communicating your intent to your readers is as important as it is to write correct code, because otherwise they might break something while maintaining your code.
It is customary in Java to call abstract classes Abstract...; in your example that would be AbstractParent.
Of course you can do it that way, but it all depends on the right business logic.There might arise a situation where you'd want to enforce a policy on people extending your code.
For example, I write an Employee class and you extend my class for writing a ProjectManager class. But suppose the business does not allow direct instantiation of Employee (like I said, just an example). So I declare my Employee class as abstract, thereby enforcing upon all extenders (read:you) of my class the rule that they can't instantiate Employee directly. (It will happen indirectly through the inheritance chain, of course, i.e. parent objects are created before child objects.)
Used properly, a person at place A controls how another person at place B will code.
A concrete class is one which has implementation (code inside) for all the methods. It does not matter whether it is derived from some other class.
public abstract class IAmAbstract{
public void writeMe(){
System.out.println("I am done with writing");
}
}
public class IAmConcrete extends IAmAbstract{
public void writeMe(){
System.out.println("I am still writing");
}
}
Abstract classes have a variety of useful properties in use with software design.
Other than the obvious differences, such as being unable to be instantiated and being able to hold abstract methods. They are useful for defining common, yet overridable, functions, holding static methods that deal with it's children in a logical manner.
My favorite is the abstract factory pattern though.
By making a factory that is the parent of all the classes it may create, it can force functionality required for creation, this actually causes an odd artefact where technically tighter-coupled code is actually easier to maintain.

Why should we declare interface methods as public? [duplicate]

This question already has answers here:
Protected in Interfaces
(15 answers)
Closed 5 years ago.
When I implement an interface method, I am forced to make it a public method.
We may have cases where we want to use either the default (like in case of access within the same package) or protected.
Can anyone please explain the reason behind this limitation?
Interfaces are meant to define the public API of a type - and only that, not its implementation. So any method (or static member) you define in an interface is by definition public.
Since an interface can't contain any concrete implementation, there is no way to call any member methods from within. And declaring such methods but leaving the calls to them to subclasses or totally unrelated clients would mean your type definition is incomplete and brittle. That is why if you need to define protected or package access members, you can do so in an abstract class (which may also contain implementation).
Maybe this will provide some answers.
To my knowledge, you use interfaces to allow people from outside your code to interact with your code. To do this, you need to define your methods public.
If you would like to force someone to override a given set of private methods, you might want to declare an abstract class with a series of abstract protected methods.
An interface is a contract that the class that implements it will have the methods in the interface. The interface is used to show the rest of the program that this class has the methods and that they could be called
EDIT: This answer is meant for C# interface implementations. In this case of Java the scenario is similar just that the syntactic analyzer wants a public keyword mentioned in the interface, which is implicitly done in C#
Interface methods are implicitly public in C# because an interface is a contract meant to be used by other classes. In addition, you must declare these methods to be public, and not static, when you implement the interface.
interface IStorable
{
void Read( );
void Write(object obj);
}
Notice that the IStorable method declarations for Read( ) and Write( ) do not include access modifiers (public, protected ..). In fact, providing an access modifier generates a compile error.
class Document : IStorable
{
public void Read( )
{
//
}
public void Write(object obj)
{
//
}
}
Just think about interfaces as Contracts to be implemented as public
If we mark a interface method as private the implementing class wont
see the method and cant override it.
If we mark a interface method as protected the implementing class
wont see the method unless it is in the same package as the
interface.
If we mark a interface method without any access modifier the
implementing class wont see the method unless it is in the same
package as the interface

What is the fragile base class problem?

What is the fragile base class problem in java?
A fragile base class is a common problem with inheritance, which applies to Java and any other language which supports inheritance.
In a nutshell, the base class is the class you are inheriting from, and it is often called fragile because changes to this class can have unexpected results in the classes that inherit from it.
There are few methods of mitigating this; but no straightforward method to entirely avoid it while still using inheritance. You can prevent other classes inheriting from a class by labelling the class declaration as final in Java.
A best practice to avoid the worst of these problems is to label all classes as final unless you are specifically intending to inherit from them. For those to intend to inherit from, design them as if you were designing an API: hide all the implementation details; be strict about what you emit and careful about what you accept, and document the expected behaviour of the class in detail.
A base class is called fragile when changes made to it break a derived class.
class Base{
protected int x;
protected void m(){
x++;
}
protected void n(){
x++; // <- defect
m();
}
}
class Sub extends Base{
protected void m(){
n();
}
}
It is widely described in below article By Allen Holub on JavaWorld
Why extends is evil.
Improve your code by replacing concrete base classes with interfaces
All of what Colin Pickard said is true, but here I want to add some of the best practices when you are writing code that may cause this kind of issue, and especially if you are creating a framework or a library.
Make all your concrete classes final by default, because you probably don't want them to be inherited. You can find this behavior as a feature of many languages, such as Kotlin. Besides, if you need to extend it, you can always remove the final keyword. In this way the absence of final on a class can be interpreted as a warning to not rely on specific functionality for other methods on this that are not private and/or final.
For classes that cannot be marked as final, make as many methods as possible final to ensure they're not modified by subclasses. Additionally, do not expose methods that are not meant to be overridden—prefer private over protected. Assume that any method not private and/or final will be overridden and ensure that your superclass code will still work.
Try to not use an inheritance ("Bar is a Foo") relationship. Instead use a helper ("Bar uses a Foo") relationship between your classes. Use interfaces rather than abstract classes to ensure that classes using this helper have a uniform interface.
Remember that almost* every extends can be replaced by implements. This is true event when you want to have a default implementation; an example of such a conversion is shown below:
Old Code:
class Superclass {
void foo() {
// implementation
}
void bar() {
// implementation
}
}
class Subclass extends Superclass {
// don't override `foo`
// override `bar`
#Override
void bar() {
// new implementation
}
}
New Code:
// Replace the superclass with an interface.
public interface IClass {
void foo();
void bar();
}
// Put any implementation in another, final class.
final class Superclass implements IClass {
public void foo() {
// implementation for superclass
}
public void bar() {
// implementation for superclass
}
}
// Instead of `extend`ing the superclass and overriding methods,
// use an instance of the implementation class as a helper.
// Naturally, the subclass can also forgo the helper and
// implement all the methods for itself.
class Subclass implements IClass {
private Superclass helper = new Superclass();
// Don't override `foo`.
public void foo() {
this.helper.foo();
}
// Override `bar`.
public void bar() {
// Don't call helper; equivalent of an override.
// Or, do call helper, but the helper's methods are
// guaranteed to be its own rather than possibly
// being overridden by yours.
}
}
The advantage of this is that the methods of the superclass are able to be sure they are working with one another, but at the same time you can override methods in your subclass.
*If you actually wanted the superclass to use your overridden method you are out of luck using this approach unless you also want to reimplement all of those methods on the "subclass". That said, the superclass calling the subclass can be confusing so it may be good to reevaluate that type of usage, its incompatibility with this approach notwithstanding.

Categories

Resources