Different rules for abstract methods in abstract class and interface - java

We cannot declare abstract methods in interface as protected and default (even if we don't mention any access specifier (default) compiler takes it as public)
but we can declare abstract method in abstract class as protected and default.
Why there are different rules for abstract class and interface?

Because abstract methods of abstract classes are meant to be hooks for subclasses. On the other hand interfaces are not concerned with implementation details - they are only about contracts with the "outside world". And a protected method is an implementation detail.

we cannot declare abstract methods in interface as protected and defaul
the purpose of Interface is to just declare contract. your client will implement it and for that it must be public.
also field in interface are public static final by default,
public you got ,static because it can't be instantiated without implementation and it must not be inherited also.
Update:
as per your question
you want to apply some strict constraint which your implementor can't see ..then what is the use of abstract method in abstract class that must be implemented by any concrete class in the inheritance hierarchy...then no one will be concrete class
public class BaseAbstractClass {
private Connection getConnection(){
//somecode
}
public boolean save(){
//get connection and do something
//return ;
}
//your implementor is left to implement it , he can use save method but can'ge see what it does i mean i doesn't have access to getConnection
public abstract void saveEntity();
}

Related

Concrete class implementing interface with lower access

Why did java make interface allow only public abstract methods?
Why are interface methods always public and not allow protected. Where in abstract class can implement protected abstract methods.
Abstract class can make lower access abstract methods right? An interface is an abstract data type that defines a list of abstract.
Can someone explain to me why it was implemented like that?
public abstract class Animal{
protected abstract void printName();
}
---Assume As Separate file ---
public class Lion extends Animal{
protected void printName(){}
}
This answers the question which eventually popped up in your comment:
why is interface methods always public and not allow protected. where in abstract class can implement protected abstract methods or even lower
It doesn't make sense to make an abstract method in an interface anything other than public, because then it wouldn't be possible for an implementing class to see it. Actually, in Java 9, there is such a thing as private interface methods. But, private interface methods cannot also be abstract, because these two modifiers mean different things. Private methods in Java 9 interfaces are intended to be consumed within the interface, e.g. by default methods. So it makes sense to have a private interface method in this case, because it is only intended to be used internally.
Here is a link to a useful blog post on this topic.

Why should I declare implemented interface methods as "public"?

interface Rideable {
String getGait();
}
public class Camel implements Rideable {
int weight = 2;
String getGait() {
return " mph, lope";
}
void go(int speed) {++speed;
weight++;
int walkrate = speed * weight;
System.out.print(walkrate + getGait());
}
public static void main(String[] args) {
new Camel().go(8);
}
}
Upon compiling the above code I've got a compilation error, related to access modifier of getGait() method. Please explain, why should I declare getGait() with public access modifier?
getGait() of Camel implements a method of the Rideable interface. All interface methods are public by default (even if you don't specify it explicitly in the interface definition), so all implementing methods must be public too, since you can't reduce the visibility of the interface method.
In the interface you have method getGait() declared as public. Even you do not state a method as a public in interface it is public.
But in your class, you have declared this method as package private. It is not allowed, because it reduces the visibility of the implemented method.
To avoid this problem. either declare this method as public in your class, or remove declaration (implements Rideable) that your class implements the interface with this method signature.
According object oriented fundamentals, interface contains only public methods. so when you implements interface, you should declare it as a public , otherwise it give you compile time error.
Thanks.
One of the basic usage of interfaces can be to check conformance.For example a class implementing Comparable interface must provide compareTo method and hence providing a mechanism to compare objects of the class.
The reason these methods being public makes sense is that any class which utilizes this conformance must be able to use these methods without any restriction.For example sort method of Arrays class will be good enough to sort objects of a class only if it implements Comparable and exposes the compareTo method(If thats the mechanism you want to provide for sorting.Of course Comparator is also there). So in a nutshell, a contract is only good enough if its readable or usable in case of interfaces(thus making methods public imperative).
In Interface, the fields are implicitly public static final and the methods in an interface are by default public.
Please read the rules of Inheritance:
http://www.codejava.net/java-core/the-java-language/12-rules-of-overriding-in-java-you-should-know
One of which says, "The overriding method must not have more restrictive access modifier". So you are ovveriding the getGait() in Camel class. If you do not provide the access modifier in methods of class then by defaults its default. Which mean you are restricting the access modifier from public to default. Hence breaking the rule of ovveriding which is why its complaining.

What is the Concrete class in java

According to this document, and many similar documents, a concrete class is described as:
A concrete class in Java is any such class which has implementation of all of its inherited members either from interface or abstract class
And can used like this:
public abstract class A {
public abstract void methodA();
}
interface B {
public void printB();
}
public class C extends A implements B {
public void methodA() {
System.out.print("I am abstract implementation");
}
public void printB() {
System.out.print("I am interface implementation");
}
}
In the above example class C is a concrete class.
Is this the only way to create a concrete class. Can you give me more info about concrete class?
A concrete class is a class that has an implementation for all of its methods that were inherited from abstract or implemented via interfaces. It also does not define any abstract methods of its own. This means that an instance of the class can be created/allocated with the new keyword without having to implement any methods first. Therefore it can be inferred that any class that is not an abstract class or interface is a concrete class.
In your code above, C will be a concrete class as it implements all abstract methods inherited from A and implemented from B. Also, it does not define any abstract methods of its own.
The simplest definition of a concrete class is that it's a class that is not abstract.
As per name suggests, concrete means Solid, it means having no any row part or unimplemented things(methods).So we can conclude that concrete classes are those classes that can be instantiated with new key word.
MyClass myClass = new MyClass();
1.concrete class is a class which can never become
an abstract or interface .It can extend or implement or both.
2.The class is said to be concrete if all its methods and variables has defined.
A concrete class in Java is any such class which has implementation of all of its inherited members either from interface or abstract class
In the above program, representing abstract as public class will sometimes show some compile time errors to define that in its own file. As simple, just avoid using public keyword or modifier while using abstract class in your program to avoid some uncertainty. Any method that is invoked using new keyword (object creation) other than abstract and interface classes is called as concrete class.

Abstract Data Type and Interface

I am new to Java. What is the difference between Abstract data type and Interface.
For Example We have a ListADT
interface MyListADT<T> {
void add(T var);
void add(T var,int pos);
void display();
T remove(int pos);
void clear();
boolean contains(Object o);
}
Where we are defining the ADT as an interface. NoW What is the difference between ADT and Interface Or ADT is an Interface
There seems to a confusion in this Q&A. The question was about "Abstract Data Type and Interface" and most of the answers concetrating about "Abstract Classes".
The terms 'abstract data type' and abstract class refer to two entirely different concepts, although both of them use the word 'abstract'. An abstract data type is a self-contained, user-defined type that bundles data with a set of related operations. It behaves in the same way as a built-in type does. However, it does not inherit from other classes, nor does it serve as the base for other derived classes. If you search about it in wiki you would see "An abstract data type is defined as a mathematical model of the data objects that make up a data type as well as the functions that operate on these objects. There are no standard conventions for defining them. A broad division may be drawn between "imperative" and "functional" definition styles." For example, in Java we have List interface. It defines a data structure with set of method to operate on but wont provide any implementaion as such.
In contrast, an abstract class is anything but an abstract data type. An abstract class is a class that is declared abstract — 'it may or may not include abstract methods'. Abstract classes cannot be instantiated, but they can be subclassed. It is not a data type. An abstract class is merely a skeletal interface, which specifies a set of services that its subclasses implement. Unfortunately, the distinction between the two concepts is often confused. Many people erroneously use the term abstract data type when they actually refer to an abstract class.
In my opinion Interfaces are Java's way of implementing "Abstract Data type"
You can read about "Abstract Data Type" in Wiki. In additiona to that if you want to know more about abstract data type in java you could refer this link, http://www.e-reading.ws/bookreader.php/138175/Abstract_Data_Types_in_Java.pdf, its really good.
Most of you might be familiar with abstract classes, Still you could read about it from http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
To add up to this confusions, Java 8 introduced something called "Default Methods", by which we could actually give implementations for methods in interface. To eliminate that confusion you can refer this stackoverflow question Interface with default methods vs Abstract class in Java 8
Try to think about it like this:
Java interface is a type, which boils down to a set of method signatures. Any type, willing to be referenced as interface must provide implementation for these signatures. In reality, there is no behaviour contract. Your implementation can do nothing and still be 'implementing' an interface.
Java abstract class is a type, with partially specified behaviour whose internal implementation for some reason must be specified in his inheritor. This class does have behaviour, which can be redefined/specified in his inheritors.
ADT is a set of expected behaviours. You assume, that after calling adt.remove(element) you call adt.get(element) and receive null.
The answer to your question is: just an interface is not enough to be an ADT.
Everything, that correctly implements your interface MyListADT<T> is an ADT. Its external behaviour must conform the ADT concept. This means, that to be considered as ADT, your type must carry implementation, which results either in abstract class or a normal class. For example: java.util.List<T> is an interface for an ADT, but java.util.ArrayList<T> and java.util.LinkedList<T> are actually ADTs, because their actual behaviour does conform the ADT concept.
The combination of data together with its methods is called an Abstract Data Type(ADT).
A Java Interface is a way to specify ( but not implement) an ADT.
It specifies the names, parameters, and return types(ie, header) of the ADT methods.
The interface does not specify the data fields (except public constants), as that is an implementation detail.
A Java Interface specifies the requirements of an ADT as a contract between the service provider ( class that implements the ADT) and the client (the user of the class).
As per [wiki] http://en.wikipedia.org/wiki/Abstract_data_type
In computer science, an abstract data type (ADT) is a mathematical model for a certain class of data structures that have similar behavior; or for certain data types of one or more programming languages that have similar semantics. An abstract data type is defined indirectly, only by the operations that may be performed on it and by mathematical constraints on the effects (and possibly cost) of those operations.
For Java programming language
you can take Java's List interface as an example. The interface doesn't explicitly define any behavior at all because there is no concrete List class. The interface only defines a set of methods that other classes (e.g. ArrayList and LinkedList) must implement in order to be considered a List.
but the bottom line is that it is a concept
In java-
interface can have only abstract method which means you can only declare the method i.e . method can have any default implementation.but abstract class can have both abstract or complete method.
if the class you are extending is abstract then your child class should either be declared as abstract or should implement all abstract method of super class.
In case -in interface you can implement as many interface you want.Here also you should implement all the abstract method of all the interfaces in your class or it should be declared as abstract.
follow these link
http://javapapers.com/core-java/abstract-and-interface-core-java-2/difference-between-a-java-interface-and-a-java-abstract-class/
http://www.codeproject.com/Articles/11155/Abstract-Class-versus-Interface
What is the difference between an interface and abstract class?
For more clearance.
Syntax and examples
syntax of abstract class
public abstract class MyAbstractClass
{
//code
public abstract void method();
}
example of abstract class
public abstract class Animal
{
abstract void walk();
}
public class Dog extends Animal
{
void walk()
{
//Implementation is done here
}
}
syntax of interface
public interface NameOfInterface
{
//Any number of final, static fields
//Any number of abstract method declarations\
}
example of interface
interface Animal {
public void eat();
public void travel();
}
implementing interface
public class MammalInt implements Animal{
public void eat(){
System.out.println("Mammal eats");
}
public void travel(){
System.out.println("Mammal travels");
}
public int noOfLegs(){
return 0;
}
public static void main(String args[]){
MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}
extending interface
//Filename: Sports.java
public interface Sports
{
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}
//Filename: Football.java
public interface Football extends Sports
{
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}
//Filename: Hockey.java
public interface Hockey extends Sports
{
public void homeGoalScored();
public void visitingGoalScored();
public void endOfPeriod(int period);
public void overtimePeriod(int ot);
}
extending multiple interfaces
public interface Hockey extends Sports, Event
extends and implements Both
interface A can extends interface B
class A can extends class B
class A implements interface A
class A extends class B implements interface A
The combination of data with its methods is called an Abstract Data Type (ADT).
A Java Interface is a way to specify an Abstract Data Type (ADT).
You can declare a class as abstract when it contains zero or more abstract methods or When an interface is implemented to a class where not all methods are not implemented.
What is the difference between Abstract data type and Interface.
Variables declared in a Java interface is by default final. An
abstract class may contain non-final variables.
Members of a Java interface are public by default. A Java abstract
class can have the usual flavors of class members like private,
protected, etc..
check this link for info

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