What is the difference between open class and abstract class?

Viewed 7507
abstract class ServerMock(param: String) {
   protected var someVar = params + "123"

   fun justMyVar() = someVar
}

Usage example:

class BaseServer(param: String) : ServerMock(param) {
   val y = someVar
}

Can this class be marked as open and not abstract?

What is the difference between open and abstract class?

3 Answers

abstract class cannot be instantiated and must be inherited, abstract classes are open for extending by default. open modifier on the class allows inheriting it. If the class has not open modifier it is considered final and cannot be inherited.

You can not instantiate an abstract class. You either need to subclass or create an anonymous class using object. In abstract classes you can just declare function without implementing them (forcing the subclass to imlement them) or provide a default implementation.

abstract class BaseClass {
  fun foo() // subclasses must implement foo
  fun bar(): String = "bar" // default implementation, subclasses can, but does not have to override bar
}

// error: can not create an instance of an abstract class
val baseClass = BaseClass()

class SubClass : BaseClass {
  // must implement foo
  override fun foo() {
    // ...
  }

  // can, but does not need to override bar
}

// declaring an anonymous class (having no name) using object keyword
val baseClass: BaseClass = object : BaseClass {
  // must implement foo
  override fun foo() {
    // ...
  }

  // it is optional implementing bar
  override fun bar(): String {
    return "somethingElse"
  }
}

A class that is neither abstract nor open is considered to be final and can not be extended.

If you want to allow subclassing you should mark it open.

class AClass

// error: This type is final, so it can not be inherrited from.
class BClass : AClass

open class CClass

class DClass : CClass

So if you want to allow BaseServer to be subclassed you should mark it open. If you also want to declare functions, but force subclasses to implement them you can replace open with abstract.

Documentation

Imagine you have 2 classes

  1. Class Person [parent class]
  2. Class Coder [sub/child class]

When you want to inherit Coder from Person you have to make Person open, so it is available to inherit from. Meanwhile you can make objects from Person itself.

When you don't need to make objects from parent class(in our case it's Person) or you don't see any meaning creating objects from it you can use abstract instead of open.

It works the same way as open does. But the main difference is that you cannot make objects from Person(parent class) anymore.

Related