How to make a class only extendable not directly usable and with a different implementation for the method by every sub class? I thought about interfaces but interfaces doesn't obligate me to initialize variables just obligates me to implement the methods I want something that obligates every single sub class to initialize a some specific variables they extend.
Add the abstract modifier. That is
public abstract class MyClass { ... }
As he said what you want is an Abstract Class, an abstract class is like a template:
Thi is what Oracle say:
Abstract Classes Compared to Interfaces
Abstract classes are similar to interfaces. You cannot instantiate them, and they may contain a mix of methods declared with or without an implementation. However, with abstract classes, you can declare fields that are not static and final, and define public, protected, and private concrete methods. With interfaces, all fields are automatically public, static, and final, and all methods that you declare or define (as default methods) are public. In addition, you can extend only one class, whether or not it is abstract, whereas you can implement any number of interfaces.
Which should you use, abstract classes or interfaces?
Consider using abstract classes if any of these statements apply to your situation:
You want to share code among several closely related classes.
You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.
Consider using interfaces if any of these statements apply to your situation:
You expect that unrelated classes would implement your interface. For example, the interfaces Comparable and Cloneable are implemented by many unrelated classes.
You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.
You want to take advantage of multiple inheritance of type.
Here is more information
https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
and you can use as he said
abstract class Name{}
Related
As Java 9 is going to allow us to define private and private static methods too in interfaces, what would be the remaining difference in interface and class?
Moreover, is Java moving towards multiple inheritance slowly?
Private interface methods in Java 9 behave exactly like other private methods: They must have a body (even in abstract classes) and can neither be called nor overridden by subclasses. As such they do not really interact with inheritance. Talking of which (and particularly multiple inheritance), there are (at least?) three kinds of it:
Inheritance of types means that one type can be another type, e.g. String is an Object. Java allowed multiple inheritance of types from day one (via interfaces).
Inheritance of behavior means that one type can inherit the behavior of another type. Before Java 8, only classes could implement methods, so there was only single inheritance of this kind. With Java 8 came default methods, which allowed interfaces to implement methods, thus giving Java multiple inheritance of behavior.
Inheritance of state means that a type inherits another type's internal state (i.e. fields). As it stands (Java 9 and everything currently proposed for future Java versions), only classes can have state, so there is only single inheritance of this kind.
As you can see private interface methods do not add anything here.
Regarding your question of how interfaces and classes compare, there are two main differences: multiple inheritance and state. Interfaces support the former, classes can have the latter. Since state is kind-of important in typical OOP, classes will remain relevant. 😉
If there were a way for an interface to force an implementation to have a particular non-public field or straight-out define one itself, the game would change and interfaces could compete with classes.
Private methods are not inherited by subclasses, so this feature doesn't affect implementation classes. I believe the private methods in interfaces allow us to share code between default methods.
Java interfaces still cannot have non-static members. That's a big difference and not multiple inheritance IMO.
Java 9 interfaces still cannot contain fields and constructors. This makes a huge difference between classes and interfaces, so Java 9 is far from multiple inheritance.
Java Interface in version 9 have private methods but static private. The feature has been introduced to allow modular methods. One function should work with one responsibility instead of using lengthy default methods. It has nothing to do with multiple Inheritance. The more private static methods, the more you will be able to write the clean and reusable code. Anyways, static methods whether public or protected can not be overridden.
Although its an old question let me give my input on it as well :)
abstract class: Inside abstract class we can declare instance
variables, which are required to the child class
Interface: Inside interface every variables is always public static
and final we cannot declare instance variables
abstract class: Abstract class can talk about state of object
Interface: Interface can never talk about state of object
abstract class: Inside Abstract class we can declare constructors
Interface: Inside interface we cannot declare constructors as purpose of
constructors is to initialize instance variables. So what
is the need of constructor there if we cannot have instance
variables in interfaces.
abstract class: Inside abstract class we can declare instance and static blocks
Interface: Interfaces cannot have instance and static blocks.
abstract class: Abstract class cannot refer lambda expression
Interfaces: Interfaces with single abstract method can refer lambda expression
abstract class: Inside abstract class we can override OBJECT CLASS methods
Interfaces: We cannot override OBJECT CLASS methods inside interfaces.
I will end on the note that:
Default method concepts/static method concepts in interface came just to save implementation classes but not to provide meaningful useful implementation. Default methods/static methods are kind of dummy implementation, "if you want you can use them or you can override them (in case of default methods) in implementation class" Thus saving us from implementing new methods in implementation classes whenever new methods in interfaces are added. Therefore interfaces can never be equal to abstract classes.
I know interface variables are always static because we can't make object of interface. But why not abstract class variables are always static? We cant make object of abstract class too
The main difference between interfaces and abstract classes is that - interfaces are just contracts, they are for specifying the signature of the methods that their subsequent concrete implementation must have, and all the methods in an interface are implicitly abstract.
In contrast, abstract classes are classes, they can have non-abstract methods with default implementation.
As quoted from JLS for the definition of an interface:
An interface declaration introduces a new reference type whose members are classes, interfaces, constants, and abstract methods. This type has no implementation, but otherwise unrelated classes can implement it by providing implementations for its abstract methods.
and the definition of an abtract class:
An abstract class is a class that is incomplete, or to be considered incomplete.
While interfaces do not do anything except specifying the pattern of the classes that implement them, abstract classes can do more - you can define their behavior - hence you can actually provide concrete implementation of their methods as well as defining their states (i.e. instance variables).
This is because the field of abstract class is then inherited by all subclasses and can be used by them. So, you can implement methods in your abstract class that deal with the logic related to such fields. You can think of an abstract class as a partially finished implementation; because it is partially finished, it cannot be constructed before it's completed by a subclass.
It is all explained by the implements vs. extends keywords: you're implementing the functionalities of an interface but are extending the capabilities of a (potentially abstract) class.
As you're extending, you inherit all of its fields and method in your instance.
You have instances of an abstract class as soon as you extend it: you're adding/changing functionalities to it, whereas an interface is merely an empty shell that you have to "fill in" with a behaviour.
so i have my programming exam this winter and one of my assignments is to explain what extends is without using a programming example.
Now i know what it is but i find it hard to explain with words how would you explain it? Like you extends which means you are a part of the class and can add additional information to the class that only your object can see i.e a Plane extends Vehicle but has its own methods called take off that allows it to fly.
How would you guys explain extends?
The extends keyword in Java has several roles, and it depends on what you extends. If C is the entity you wish to extend.
You cannot extend it at all if C is a non abstract class and is final;
If C is a non-final, non-abstract class:
you can extend it so as to add constructors;
you can override any methods of C which are not declared final;
you can define additional instance variables, methods etc.
If C is an abstract class, and you provide a concrete (ie, non abstract) implementation of it:
you must provide constructors which call this abstract class' constructors -- all of them;
you must provide implementations of methods which are declared abstract in the extended class;
you may override implementations of methods of this class which are not abstract;
you cannot override implementations of methods in this class which are declared final;
you may add additional constructors, instance variables etc;
If C is an interface:
you can only declare an interface extending another; you cannot implement a class extending an interface (that is implements).
And, more generally, you can implement several interfaces but only extend one class/abstract class (Java does not have multiple inheritance).
Answer certainly to be edited, feel free to add comments/questions/etc
You can find examples all around you.....
eg:Animals and different variety of animals
Vehicles, with different vehicles having some common properties and some specific properties.
Shapes with common properties like area, perimeter etc, where different shapes calculate these functions differently.
What is the difference between an abstract class and an interface?
Interfaces are stateless. They cannot gave variables, though they can have constants.
Also, interfaces provide the 'design by contract ' capability.
Abstract classes force a concrete implementation, where interfaces allow more flexibility because any class that implements that interface can be substituted at run time.
Also, since interfaces simply describe behavior that is exposed, not the implementation, then thet allow for multiple inheritance.
Also abstract classes are more a design convenience as they provide for compiler enforcement in that subclasses must implement abstract methods.
Interfaces and abstract classes are related, but serve different purposes.
At runtime the type of object is checked and the corresponding class method invoked.
This is also called late binding.
This is done by the runtime VM not by the programmer thus taking that If Else test out of your program code. So, your code is more flexible and does not depend on the class type to resolve the correct method to call. Thus us also called polymorphism.
An abstract class can have methods implemented. An interface cannot. Also a class can only extend one abstract class, but can implement many interfaces.
Use of interface : There are a number of situations in software engineering when it is important for disparate groups of programmers to agree to a "contract" that spells out how their software interacts. Each group should be able to write their code without any knowledge of how the other group's code is written. Generally speaking, interfaces are such contracts.
One benefit of using interfaces is that they simulate multiple inheritance. All classes in Java (other than java.lang.Object, the root class of the Java type system) must have exactly one base class; multiple inheritance of classes is not allowed. Furthermore, a Java class may implement, and an interface may extend, any number of interfaces; however an interface may not implement an interface.
Another use of interfaces is being able to use an object without knowing its type of class, but rather only that it implements a certain interface.
Difference bw abstract class and interface : Abstract class is a class which contain one or more abstract methods, which has to be implemented by sub classes. An abstract class can contain no abstract methods also. A Java Interface can contain only method declarations and public static final constants and doesn't contain their implementation. The classes which implement the Interface must provide the method definition for all the methods present. An abstract class means the class must be extended. An abstract class must be extended by first concrete class in the inheritance tree. In the abstract class we can have both declaration and definition of a method but in interfaces there are only method signatures, no definition at all. An interface is like a 100% pure abstract class. A class can extend only one class but can implement multiple interfaces. Interfaces provides multiple inheritance without causing deadly diamond of death problem.
Extensive discussions here :
Abstract classes and interfaces in C#
Do/can abstract classes replace interfaces?
Disadvantage : when you have an 1000 class implementing an interface in your library, tomorrow if you want to have an additional method in interface , then changes should be reflected everywhere
This question already has answers here:
When to use an interface instead of an abstract class and vice versa?
(26 answers)
Closed 5 years ago.
In Java, you can create an abstract class that contains only abstract methods. On the other hand, you can create an interface that declares the same methods. That being the case, can you use abstract classes instead of interfaces?
Not always:
a class can extend only one class
a class can implement more than one interface
Sun docs make a more detailed comparison:
Abstract Classes versus Interfaces
Unlike interfaces, abstract classes can contain fields that are not static and final, and they can contain implemented methods. Such abstract classes are similar to interfaces, except that they provide a partial implementation, leaving it to subclasses to complete the implementation. If an abstract class contains only abstract method declarations, it should be declared as an interface instead.
Multiple interfaces can be implemented by classes anywhere in the class hierarchy, whether or not they are related to one another in any way. Think of Comparable or Cloneable, for example.
By comparison, abstract classes are most commonly subclassed to share pieces of implementation. A single abstract class is subclassed by similar classes that have a lot in common (the implemented parts of the abstract class), but also have some differences (the abstract methods).
In some cases you can use an abstract class instead of interface. However, it is hardly ever a good idea to do so. In general you should use the rule:
Interfaces specify behaviour.
Abstract classes specify implementation.
The other "problem" with using abstract classes is that you can then no longer implement mixins, that is you can implement multiple interfaces, however you can only extend one abstract class.
One point missing from the answers here is the idea of who will be implementing the interface.
If your component wants to return instances of abstract types to its callers, where the concrete types are defined internally and hidden from callers, use an interface. Conversely, if your component consumes or accepts instances of abstract types that its callers must implement, abstract classes are usually a better choice.
Anticipating evolution and maintaining binary compatibility tips the scales here. With an abstract class, you can add methods and, if you provide a base implementation, existing implementations of the abstract class will continue to work fine. With an interface, adding a method breaks binary compatibility, for no existing implementation could possibly continue to compile properly without changing to define the new method.
The Apache Cactus project has a good discussion on how to resolve these obligations.
To answer your question, yes you could use an abstract class (providing no implementation) instead of an interface but I'd consider this bad practice:
You've used up your "one-shot" at inheritance (without gaining any benefit).
You cannot inherit from multiple abstract classes but you can implement multiple interfaces.
I would advocate the use of abstract classes more in situations where you wish to provide a partial implementation of a class, possibly delegating some behavior to concrete subclass implementations.
A class in java can inherit from multiple interfaces, but only from one abstract class.
An interface cannot define any code, in an abstract class, you can define code (i.e. default behaviour of methods)
Abstract classes and interfaces are complementary.
For instance when creating an API you will want to present interfaces to the client, so that you may always completely change the implementation whereas he does not have to change its code and the user does not rely on implementation when building using your API but just on methods contracts.
Then you will have abstract classes partly implementing these interfaces, in order to
share some common code, which might be used in all (or almost all) implementations for interface, which is obvious
provide default behaviour which could be overridden in 'real' implementations, for instance a toString() method using interfaces methods to create a textual representation of the implementation
preserve implementations compatibility after interface changes, for instance when you add a new method in your interface, you also add a default implementation in the abstract class so that implementations (for instance those made by the user) extending the abstract class still work without changes
Interfaces are much cleaner and light weight. Abstract classes make you dependent on it heavily as you cannot extend any other classes.
Have a look at the interesting article "Why extends is evil" to get an idea about the differences between interface implementation and class inheritance (beside the obvious multi- single restrictions)
Abstract classes are the partial implementation of Abstraction while Interfaces are the fully implementation of Abstraction.Means in Abstract classes we can put methods declaration as well as method body.
We can't create an object of Abstract classes(association) and reuse the class by inheritence(not by association).
By default in interfaces all declared variables are static final and All methods are public.
For Example: In JDK there are only few abstract classes and HttpServlet is one of them which is used in Servlet.So we can't create object of HttpServlet and it can be used only by inheritence.
Main use of interface is when you create the reference of interface and call the method of particular class that's resolved at runtime. So it's always better idea to create reference of interface to call the method.
Interfaces can only hold abstract method, also interfaces can implement multiple interfaces to any class. But an abstract hold abstract and non abstract methods, and abstract methods cannot extend to more then one class.