We use abstract classes if we need to keep an implemented method and method definitions while we use interfaces if we need to keep just the method definitions. But in java and C# we can use default methods and static methods to include implementations in interfaces. So what is the use of abstract classes if we can achieve what it is intended to do by using interfaces?
There are some reasons to have abstract classes.
Abstract classes can inherit interfaces, but not vice versa
Abstract classes can inherit interfaces. However, interface cannot inherit abstract class:
public interface ABar { }
public abstract class Bar : IFoo { }
However, this is not eligible:
public interface IFoo : ABar
{
}
public abstract class ABar
{
}
Abstract classes can have constructors, fields (can hold state)
Abstract classes can have constructors, fields. By having fields, it is possible to hold state. However, interface cannot have them.
public abstract class ABar
{
public int test; // some state
public ABar()
{
}
}
I want to ask a question that I have some clues about, but I don't want to influence the answers I will get. I have the following class hierarchy:
abstract class MyAbstractClass {
fun displayStuff(id: String) {
println("My id is $id.")
}
}
interface MyInterface {
fun displayThis() {
displayStuff("some-value")
}
fun displayStuff(id: String) // Not implemented here
}
class MyConcreteClass(): MyAbstractClass(), MyInterface {
fun doStuff() {
displayThis()
}
}
fun main() {
val result = MyConcreteClass()
result.doStuff()
result.displayStuff("id")
}
What's wrong with this design, and how do you suggest I fix it?
It would probably not be a bad idea to extract the displayStuff into another interface. Then MyAbstractClass and MyInterface can both derive from the same interface.
One overrides the displayStuff function, hence providing something like an abstract base implementation for the interface.
The other one is using the function in a specific way, thereby extending the functionality of the interface.
interface DisplayStuff {
fun displayStuff(id: String)
}
abstract class MyAbstractClass: DisplayStuff {
override fun displayStuff(id: String) = println("My id is $id.")
}
interface MyInterface : DisplayStuff {
fun displayThis() = displayStuff("some-value")
}
I have code in Swift.
enum QuestionnaireViewMode {
case add(input: Add)
case edit(input: Edit)
enum Add {
case building(input: BuildingInput)
case car(input: CarInput)
case park
struct BuildingInput {
let address: String
let placeName: String
}
struct CarInput {
let name: String
}
}
enum Edit {
case profile(input: ProfileInput)
struct ProfileInput {
let name: String
}
}
}
This is enum class which very easy to use, for example i can create different type of object just like this: .add(input: .car(input: .init(name: "bmw"))). But for me not clear enum classes in kotlin, i found some similar - sealed class and i tryed converted to:
sealed class QuestionnaireViewMode {
sealed class add(input: Add)
sealed class edit(input: Edit)
sealed class Add {
sealed class building(input: BuildingInput)
sealed class car(input: CarInput)
sealed class park
data class BuildingInput(val address: String, val placeName: String)
data class CarInput(val name: String)
}
sealed class Edit {
sealed class profile(input: ProfileInput)
data class ProfileInput(val name: String)
}
}
is this correct?
Your sealed classes need to extend their parent. And you are using sealed class instead of fun for your builder functions, which doesn’t make sense. But since these are classes you don’t need that because you can call the constructors directly. Also, since you have no commonly shared state, these can be sealed interfaces instead of sealed classes, which is a little simpler because you don’t have to worry about constructors.
Here is how I would design it:
sealed interface QuestionnaireViewMode {
sealed interface Add: QuestionaireViewMode {
data class BuildingInput(val address: String, val placeName: String): Add
data class CarInput(val name: String): Add
}
sealed interface Edit: QuestionaireViewMode {
data class ProfileInput(val name: String): Edit
}
}
Usage:
val myInput: QuestionaireViewMode =
QuestionaireViewMode.Add.CarInput(“bmw”)
I have a problem to chose the between an abstract class without abstract methods OR a base class with an interface.
I have two implementation in my mind:
1.
Let's say I have a AbstractRenderer:
abstract class AbstractRenderer
{
protected $shape;
public function __construct(AbstractShape $shape)
{
$this->shape = $shape;
}
public function render(): string
{
return $this->shape->generate()->asArray();
}
}
and the WebRenderer would be like this:
class WebRenderer extends AbstractRenderer
{
}
2.
Have a base class and an interface like this:
Interface InterfaceRenderer
{
public function __construct(AbstractShape $shape);
public function render(): string;
}
and a base class that impediments the interface:
class BaseRenderer implements InterfaceRenderer
{
protected $shape;
public function __construct(AbstractShape $shape)
{
$this->shape = $shape;
}
public function render(): string
{
return $this->shape->generate()->toString();
}
}
again, my WebRenderer would be like this:
class WebRenderer extends BaseRenderer
{
}
I don't know which is the correct implementation, or there is a better way to implement this and what is the pros and cons of each.
Thanks
From the Renderer client’s perspective the 2 solutions are basically identical. As long as they depend on an abstract object (interface or an abstract class), you’ll have benefits of polymorphism. You’d lose those if you make them depend on WebRenderer (concrete object).
Interface’s benefits over abstract classes
doesn’t occupy inheritance
no fragile base class problem
Abstract classes provide
static methods (in many languages interface can’t have these)
protected implementation
I am new to Kotlin and I am confused between open and public keywords. Could anyone please tell me the difference between those keywords?
The open keyword means “open for extension“ - i.e. it's possible to create subclasses of an open class:
The open annotation on a class is the opposite of Java's final: it allows others to inherit from this class. By default, all classes in Kotlin are final, which corresponds to Effective Java, Item 17: Design and document for inheritance or else prohibit it.
You also need to be explicit about methods you want to make overridable, also marked with open:
open class Base {
open fun v() {}
fun nv() {}
}
The public keyword acts as a visibility modifier that can be applied on classes, functions, member functions, etc. If a top-level class or function is public, it means it can be used from other files, including from other modules. Note that public is the default if nothing else is specified explicitly:
If you do not specify any visibility modifier, public is used by default, which means that your declarations will be visible everywhere
class A { ... } in Java is equal to open class A { ... } in Kotlin.
final class B { ... } in Java is equal to class B { ...} in Kotlin.
It is not related with public.
In Kotlin, everything without access modifiers is public by default. You can explicitly say public in the definition, but it is not necessary in Kotlin.
So,
public class A { ... }
and
class A { ... }
are the same in Kotlin.
I put here just for my memo, maybe useful for someone else :
open class in kotlin means that a class can be inherited because by default they are not:
class Car{....}
class Supercar:Car{....} : // give an error
open Car2{....}
class Supercar:Car2{....} : // ok
public class in Java is about the visibility of class (nothing to do with inheritance : unless a class in java is final, it can be inherited by default).
In kotlin all the class are public by default.
open method in kotlin means that the method can be overridden, because by default they are not.
Instead in Java all the methods can be overridden by default
The method of an open class cannot be overridden by default as usual (doesn't matter if the class is open), they must be declared that they can be overridden :
open class Car{
fun steering{...}
}
class Supercar:Car{
override fun steering {...} // give an error
}
open class Car2{
open fun steering{...}
}
class Supercar:Car2{
override fun steering {...} // ok
}
for more details : https://kotlinlang.org/docs/reference/classes.html
public: public keyword in Kotlin is similar to java it is use to make the visibility of classes, methods, variables to access from anywhere.
open: In Kotlin all classes, functions, and variables are by defaults final, and by inheritance property, we cannot inherit the property of final classes, final functions, and data members. So we use the open keyword before the class or function or variable to make inheritable that.
open is opposite to Final in java.
If the class is not 'open', it can't be inherited.
class First{}
class Second:First(){} // Not allowed. Since 'First' is Final(as in Java) by default. Unless marked "open" it can't be inherited
Don't get confused with open and public. public is a visibility modifier
class Third{} // By default this is public
private class Fourth{}
class Fifth{
val third = Third() // No issues
val fourth = Fourth() // Can't access because Fourth is private
}
All classes, methods, and members are public by default BUT not open
Keyword open in kotlin means "Open for Extension"
means if you want any class to be inherited by any subclass or method to be overriden in subclasses you have to mark as open otherwise you will get compile time error
NOTE: abstract classes or methods are open by default you do not need to add explicitly.
OPEN VS FINAL VS PUBLIC
OPEN :
child class can access this because they are inherited by its parent.
In Kotlin you need to add 'open' keyword unlike java whose all classes are 'open' by default
Example :
Kotlin : open class A () {}
Java : class A () {}
FINAL :
child class can't access or inherit.
In JAVA you need to add 'final' keyword unlike kotlin whose all classes are 'final' by default
Example :
Kotlin : class A () {}
Java : final class A () {}
PUBLIC : Any class whether its inherited or not can access its data or methods.
Example in Kotlin :
//Final
class DemoA() {
protected fun Method() {
}
}
class DemoB() : DemoA {
Method() // can't access
}
//OPEN
open class DemoA() {
protected fun Method() {
}
}
class DemoB() : DemoA {
Method() // can access
}
//Public
class DemoA() {
fun Method() {
}
}
class DemoB() {
val a = DemoA()
a.Method() // can access
}
Example in Java :
//FINAL
final class DemoA() {
protected void name() {
}
}
class DemoB() extends DemoA {
name(); // Can't access
}
//Open
class DemoA() {
protected void name() {
}
}
class DemoB() extends DemoA {
name(); // Can access
}
//Public
class DemoA() {
void name() {
}
}
class DemoB(){
DemoA a = new DemoA()
a.name(); // Can access
}
Summarized answer (Kotlin)
The defaults of declarations of classes, methods, and properties are
(public + final). final prevents any inheritance attempts.
In order to be able to extend a class, you must mark the
parent class with the open keyword.
In order to be able to override the methods or properties, you must
mark them in the parent class with the open keyword, in addition to
marking the overriding method or parameter with the override keyword.
public is just encapsulation, it affects the visibility of classes/ methods. Public will make them visible everywhere.
Reference