+ 1

Difference Between class interface and abstract class ?with example...pls

Java

3rd Jul 2019, 2:14 PM
Nag Raj
3 Antworten
0
abstract class can has abstract methods without body, but can include normal methods with body too interface only heads of methods and its parameter types
3rd Jul 2019, 7:09 PM
zemiak
0
An interface contains only the prototypes of methods and abstract methods. They require other classes to "implement" those methods. An abstract class is a class that contains at least one abstract method. This class requires subclasses to "inherit" and implement those abstract methods.
3rd Jul 2019, 10:46 PM
Gilbert Keys
Gilbert Keys - avatar
0
An abstract class is a lot like a normal class, which is meant to be subclassed to serve its purpose. It will typically declare methods that its subclasses need to have, but that it itself doesn't define. Such methods are abstract. But beside that, an abstract class may have instance fields, constructors that will be called when the constructors of its subclasses are called, and it may define methods that aren't abstract. In other words, it may define some state and behavior like any class does, creating most of a class, but it lacks some method definitions to be complete. Or it's just meant to be only used through subclasses. Something like that: public abstract class Pet { private final String name; protected Pet(String name) { this.name = name; } public String getName() { return name; } public abstract String cry(); @Override public String toString() { return name + " is a pet that goes " + cry(); } } Also, one class can only extend one abstract or non-abstract other class. Interfaces are purely abstract. They define *no* state at all and *no* behavior at all. They define a sort of "contract" that any class implementing them must conform too, in the form of a set of methods they need to define and that therefore can be called on them. They define no constructors. No instance fields. The methods they declare are abstract only. Interfaces make absolutely *zero* assumption about how the classes that will implement them, will make the actual implementation. Internal state, actual behavior implementation, that's the problem of the classes and no business at all of the interface. The classes are 100% free to do what they want. interface StringDateConverter { String dateToString(LocalDate date); LocalDate stringToDate(String s); } And interfaces can extended as many other interfaces as they want, and classes may implement as many interfaces as they want, in addition or not to extending one class.
4th Jul 2019, 9:10 AM
kumesana