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

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

Related

Is it possible to overload abstract methods in an abstract Java class, but implement only one of the overloaded methods in subclass?

I have an abstract class (showing only the relevant parts) with two overloaded methods.
abstract public class Component {
...
abstract protected void createPhysics();
abstract protected void createPhysics(Comp1D[] comp1DS);
...
}
In the subclasses which extend this abstract class I only want to use either the one with arguments or the one without, but never both of them. For example
public class Comp1D extends Component{
...
protected void createPhysics(Comp1D[] comp1Ds){
...
}
}
and
public class Comp3D extends Component{
...
protected void createPhysics(){
...
}
}
Of course this won't compile this way since the other createPhysics method is not implemented in the subclass. My quick and dirty solution would be to implement both methods in subclasses, but the unused method would have empty body.
Is there a more elegant way to solve it in Java 8?
With abstract methods, there is not. And on a syntactical level, it would not be sound either. If one has a Component, one can call both methods. How should one know which one is implemented and which one is not?
One could define both method in the abstract class and let them throw, for example, an UnsupportedOperationException, thus forcing sublcasses to override (at least one of) those methods if they wish to not throw such an exception. This, however, seems like a workaround for another problem.
I would suggest re-evaluating the overall architecture of that section and find another solution to the problem. For example, maybe two separated classes and handler for those classes would yield a cleaner architecture.
The question is, why do you want to use an Abstract class here. What if you plan to use an interface, with default implementations. You can implement the interface and override only the required method
The idea of using abstract class is when you want to define common method signatures in the class and force sub-classes to provide implementation for such methods. From this point of view the way you are trying to implement abstract class doesn't make much sense.
You can also use abstract class to define a base type to support O-O features like polymorphism and inheritance and i think this is what are you trying to do .
If this is the case i suggest to declare an abstract class without abstract methods or declare an interface with default implementation for both methods and then you can override in implementation classes.
As #Turning85 pointed out, such an implementation would not make much sense.
Either you want to give your successor classes the flexibility to implement both of the methods according to their own specific needs or you want to take this complexity away from them and implement the whole logic in the abstract class, where you could have something like this:
abstract class Component() {
protected void createDefaultPhysics() {
//implement
}
abstract protected void createPhysics(Comp1D[] comp1DS);
}
and your concrete classes:
public class Comp1D extends Component{
protected void createPhysics(Comp1D[] comp1Ds){
if(comp1Ds == null) {
createDefaultPhysics();
}
}
}

is abstract a must or not?

As you know, in a java interface, all methods have to be defined as abstract. But when I define a method as not typing abstract, the compiler says it is okay. I know that an abstract method must not have a body. Does a method somewhere in an interface necessarily have a name abstract or not? : What i mean is, what is the difference between:
public interface blabla {
public void aMethod();
//or
public abstract void aMethod();
}
No, marking an interface method as abstract has no meaning and is never required.
All interface methods are implicitly abstract (and public too btw).
From the JLS:
Every method declaration in the body of an interface is implicitly abstract, so its body is always represented by a semicolon, not a block.
Every method declaration in the body of an interface is implicitly public.
For compatibility with older versions of the Java platform, it is permitted but discouraged, as a matter of style, to redundantly specify the abstract modifier for methods declared in interfaces.
It is permitted, but strongly discouraged as a matter of style, to redundantly specify the public modifier for interface methods.
Related question (+ answer with a historical reference to a statement saying that abstract was once required for interface methods):
Java abstract interface
See the sample example below
interface xyz
{
void methodA();
}
Save this to xyz.java
Now compile this using javac tool
and then use the command given belo
javap xyz
the output would be
Compiled from "xyz.java"
interface xyz {
public abstract void methodA();
}
That means when you compile an interface, compiler makes its signature to public and abstract by default.
So it is not necessary to use abstract keyword for any method of interface.
I don't know that they have to be defined as abstract. Probably because they don't. See Oracle's tutorial.
you don't need to specify abstract (default) because within an interface it does not make sense as all the method of the interface needs to be implemented
All methods in an interface are abstract by definition.
You can't create an object out of an interface (e.g., using Interface i = new Interface();) so there's no difference between marking a method as abstract or not.
Any class that implements the interface needs to decide whether to implement it or to let a subclass do it. So as far as the interface is concerned, all methods are abstract by default.
An abstract method provides no implementation. A class which has an abstract method is necessarily abstract, which means that you cannot create instances of this class. To create an instance of that class, you need to subclass and provide non-abstract overwrites for the abstract methods.
An interface never provides an implementation of its methods and it cannot be instantiated. Therefore every method of an interface is per definition abstract. You do not need to provide the keyword abstract when declaring a method in an interface. And by convention the keyword abstract is not used within an interface.
The methods of an interface don't have to be explicitly defined as abstract because they are implicitly abstract and public as defined in the Java Language Specification ยง9.4. A redundant declaration is perfectly legal though.
If you forgot to put abstract keyword before interface method, Java will implicitly put public abstract keyword before it. Because all interface methods must be abstract.

Change the access modifier of an overridden method in 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();
}

what is a abstract method on a interface in java [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Why would one declare a Java interface method as abstract?
I found the following code in one of our ejb interfaces. Does anyone know what the abstract does in the interface? If you do please also explain why it might be needed or provide a reference to read about it =)
#Local
public interface IDomasOrderProcessor {
public abstract void executeOrderLines(List<OrderLine> lines);
public abstract void setupJob(List<OrderLine> lines);
public abstract void setupJob(OrderLine line);
}
abstract is redundant in this case. All methods defined on an interface are public and abstract by definition.
Excerpt Java Language Specification section 9.4
Every method declaration in the body of an interface is implicitly
abstract, so its body is always represented by a semicolon, not a
block.
Every method declaration in the body of an interface is implicitly
public.
Both public and abstract modifiers are implicit in interfaces and should be avoided.
A method in an interface is public and abstract by definition. I have heard some people say they feel that explicitly declaring them like that makes it clearer, but to me it seems like extra noise.
As per this
document all the methods of interface is public and abstract, so there is no mean to define explicitly abstract method inside the interface.

Abstract class with all concrete methods

Are there some practical programming situations for someone to declare a class abstract when all the methods in it are concrete?
Well you could be using a template method pattern where there are multiple override points that all have default implementations but where the combined default implementations by themselves are not legal - any functional implementation must subclass.
(And yes, I dislike the template method pattern ;))
An abstract class is a class that is declared abstract - it may or may not include abstract methods. They cannot be instantiated so if you have an abstract class with concrete methods then it can be subclassed and the subclass can then be instantiated.
Immagine an interface whose declared methods usually show the same default behavior when implemented. When writing a class that needs to support the interface you have to define said default behavior over and over.
To facilitate implementation of your concrete classes you might want to provide an abstract class providing default behavior for each method. To support the interface in a concrete class you can derive from the abstract class and override methods if they deviate from the standard behavior. That way you'll avoid the repeated implementation of the same (redundant) default behavior.
Another possible use case is a decorator which delegates all calls to the wrapped instance. A concrete decorator implementation can override only those methods where functionality is added:
public interface Foo {
public void bar();
}
public abstract class FooDecorator implements Foo {
private final Foo wrapped;
public FooDecorator(Foo wrapped) { this.wrapped = wrapped; }
public void bar() { wrapped.bar(); }
}
public class TracingFoo extends FooDecorator {
//Omitting constructor code...
public void bar() {
log("Entering bar()");
super.bar();
log("Exiting bar()");
}
}
Although I don't really see the necessarity to declare FooDecorator as abstract (non-abstract example: HttpServletRequestWrapper).
Previous answers already hit the main issues, but there's a minor detail that might be worth mentioning.
You could have a factory that returns instances of (hidden) subclasses of the abstract class. The abstract class defines the contract on the resulting object, as well as providing default implementations, but the fact that the class is abstract both keeps it from being instantiated directly and also signals the fact that the identity of the "real" implementation class is not published.
Wondering why no one has pointed to the Practical Example of MouseAdapter:
http://docs.oracle.com/javase/6/docs/api/java/awt/event/MouseAdapter.html
An abstract adapter class for receiving mouse events. The methods in
this class are empty. This class exists as convenience for creating
listener objects.
Nice question :)
One thing is for sure ... this is certainly possible. The template suggestion by krosenvold is one good reason for doing this.
I just want to say that a class must not be declared abstract just for preventing it's instantiation.
This is referred in the Java Language Specification Section 8.1.1.1
When you have an important class but the system cannot create an instance fo this class, because
this class is parent of a lot of classes of the system;
this has a lot of responsability (methods used by a lot of class) for domain's requires;
this class not represents a concrete object;
Servlet Example:
All methods are concrete,
but the base class is useless by itself:
DeleteAuthor.java
Abstract class with concrete doGet method.
doGet calls file pointed to in protected string sql_path.
sql_path is null.
DeleteAuthorKeepBook.java
extends abstract class DeleteAuthor
sets sql_path to delete_author_KEEP_BOOK.sql
DeleteAuthorBurnBook.java
extends abstract class DeleteAuthor
sets sql_path to delete_author_BURN_BOOK.sql

Categories

Resources