In other programming language like Java and C#, when we want to call the method and want to access the members of a class then we make the object of the class and with the help of that object, we access the members of the class. like:-
class ToBeCalled {
fun callMe() = println("Codinglance:)")
}
fun main(args: Array<String>) {
val obj = ToBeCalled()
// calling callMe() method using object obj
obj.callMe()
}
The static keyword
In some other languages like Java and C#, they have static keyword to declare the members of the class that can be use without making any object means you can call them with the help of class name.
public class MyClass {
public static void myMethod() {
// do something
}
}
Here we can call myMethod without making instance:-MyClass.myMethod();
In kotlin to use this we use a companion object
Companion object
In Kotlin, if you want call a function or any member function without making the instance of the class then you can use companion object for that you have to write function or any member function as a member of a companion object inside the class. So, by declaring the companion object, we can easily access the members of the class by class name only.
To create a companion object in kotlin, you just need to add the companion keyword in front of the object declaration.
class CompanionClass {
companion object {
}
}
val obj = CompanionClass.Companion
So, here is the example of a companion object in Kotlin:
class ToBeCalled {
companion object Test {
fun callMe() = println("Codinglance :)")
}
}
fun main(args: Array<String>) {
ToBeCalled.callMe()
}
The output of the above code is “ Codinglance ”
Object Declarations
Singleton is an object-oriented pattern where a category can have just one instance (object).
For example, you’re working an application having SQL database backend. you wish to form a connection pool to access the database while reusing the identical connection for all clients. For this, you’ll be able to create the connection through singleton class in order that every client get the identical connection.
Kotlin provides a simple thanks to create singletons using the item declaration feature. For that, object keyword is employed.
object SingletonExample of sophistication
... .. ...
}
Object Expressions
Object expressions create objects of anonymous classes, that is, classes that are not explicitly declared with the category declaration. Such classes are handy for one-time use. you’ll be able to define them from scratch, inherit from existing classes, or implement interfaces. Instances of anonymous classes also are called anonymous objects because they’re defined by an expression, not a name.
window.addMouseListener(object : MouseAdapter() {
override fun mouseClicked(e: MouseEvent) { /*...*/ }
override fun mouseEntered(e: MouseEvent) { /*...*/ }
})
Kotlin Visibility modifiers
Visibility modifiers provide the features of the accessibility of objects, classes, interface, functions, constructors properties and their setters.By default all the classes and functions are actually by default public in nature show in kotlin everything is public in nature by default always remember.In case of Kotlin we have the 4 visibility modifiers:-
- Public
- Protected
- internal
- private
Public
In Kotlin, public is the default modifier. Public modifier provide accessibility from everywhere in the project. it is a default modifier in kotlin language. if any class interface etc are not specified with any access modifier than that class interface etc are used in public scope
Example
class A {
// public by default
var int = 20
}
public class B {
var int2 = 30
fun display() {
println("Accessible everywhere")
}
}
Protected
In Kotlin, the protected modifier allow accessibility to the declaring class and its subclasses. The protected modifier can not be defined at the top level. A Protected modifier with class or interface allowed visibility to its class or subclass only. A protected declaration in its class is also protected modifier and let it is explicitly changed.
Example
open class A {
// protected variable
protected val int = 10
}
// derived class
class B: A() {
fun getvalue(): Int {
return int // accessed from the subclass
}
}
fun main(args: Array<String>) {
var a = B()
println("The value of integer is: "+a.getvalue())
}
output
The value of integer is: 10
Overriding of protected modifier
Some time we need to add open keyword to the the protected variable or function to override in the derived class. In the below example, we will see how to overridden the int variable.
example
// base class
open class test {
open protected val int = 20 // protected variable
}
// derived class
class test2: test() {
override val int = 30
fun getvalue():Int {
return int // accessed from the subclass
}
}
fun main(args: Array<String>) {
var a = test2()
println("The overridden value of integer is: "+a.getvalue())
}
Output
The value of integer is: 30
Internal
The internal modifier are newly added in Kotlin, it is not available in Java. The internal modifier make the field accessible only inside the module in which it is implemented.
Example
internal class A {
}
public class B {
internal val int = 10
internal fun display() {
}
}
private
A private modifier allows the declaration to be accessible only within the block in which property field etc are declared. the private modifier declaration does not allowed to access the outside the scope .private package can be accessible within that specific file.
Example
private class A {
private val int = 10
fun display()
{
println(int) // we can access int in the same class
println("Accessing int successful")
}
}
fun main(args: Array<String>){
var a = A()
a.display()
println(a.int) // can not access 'int': it is private in class A
}
output
10
Accessing int successful
Constructor Visibility
As we know by default constructors are public, but with the help of modifiers we can also change the visibility of constructor.
class A (name : String) {
// other code
}
We have to explicitly specify with constructor keyword while we are changing the visibility.
class A private constructor (name : String) {
// other code
}
Conclusion
In this article, we explored what is companion object in kotlin, what is static keyword, what are visibility modifiers in kotlin,why we use then what is the importance of them .In this article we try to understand with demo how to use them.these are very useful concept in kotlin which is very helpful while coding in any project this concept help to reduce lots of boiler plate code and make the code very simple and easy to understandable.