Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Kotlin private constructor

Introduction to Kotlin private constructor

The kotlin Private Constructor is one of the constructor types, and it is used to stop the object creation for the unwanted case; if the user has decided to create the object for themselves accordingly, the memory will be allocated for the specific instance and also the class methods which is used for referring the main method instance the private constructor is also called as the singleton pattern. The constructor provides the custom visibility in the class header using the constructor parenthesis. The default function will be applied directly to the objects related to the standard libraries on kotlin language.

Syntax:

In kotlin language has many default functions, variables, and keywords, more than ever. The classes are the main role for declaration, and these class variables and methods will call it on the main method using the constructor. Here the constructor will use the private modifier.

class name private constructor(){
--some methods—
}
companion object
{
private var refs : name?=null
fun getInstance(): name{
---some logic codes---
}
}

The above code is the basic syntax for implementing the private constructor like nothing but the singleton pattern used to call the class attributes. Kotlin Instance() method is used to call and execute the private constructor object.

How private constructor works in Kotlin?

In the kotlin language, we used class, methods, variables for implementing the application user-defined logic. Classes in kotlin are called with the default constructor whenever the object is created. Basically, kotlin creating the object in different ways; in this case, we used private constructor as the keyword used along with the kotlin class. The primary constructor has the parameter arguments that can be used in the initializer blocks and their properties to be initialized in the class body.

If the class constructor has annotations and other parameters required by the modifiers and the secondary constructor, which needs to delegate to the primary constructor directly or indirectly through the secondary constructor. The delegation concept, which involves the constructor of the same and other different classes, is done using this keyword in the constructor. The constructor arguments which is used for the class to have the visibility for creating an instance of the nested inner and outer class. We can use the parent and child class relationship in the kotlin code, so the inheritance is applicable to the public and private in the same package. But the singleton instance is used with the help of the getInstance() method to perform the operations.

Examples of Kotlin private constructor

Different examples are mentioned below:

Example #1

Code:

class new private constructor() {
companion object {
fun demo() {
println("Welcome To My Domain its a first example related to the kotlin private constructor")
var vars = "Please enter your input values"
}
var p: Int = 3
var empid:Int = 2021
var empName:String="sivaraman"
var empSalary:Int=25000
var empAddress:String="Flat 12C, Sathya Enclave, Sathyamoorthy Nagar, Muthamizh Theru, chengalpattu district, chennai-600063"
fun details(){
println("Your details are: $p")
p++
}
fun empdetails(){
println("Welcome To My Domain this is the first example regarding the kotlin private constructor and also the employee details are needed for their security purpose")
println("${this.empid}")
println("${this.empName}")
println("${this.empSalary}")
println("${this.empAddress}")
println("We have entered the student details like employee id, employee name, employee salary, employee Address etc the information’s are encrypted and it is stored in the separated database server")
}
}
}
class new1{
fun exam() = println("Have a nice day users please keep on continue to spent with our application")
var stdid:Int = 83
var stdName:String="sivaraman"
var stdRollno:Int=41
var stdAddress:String="Flat 12C, Arvind Enclave, Sathyamoorthy street, Srinivasa nagar, chengalpattu district, chennai-600063"
fun stddets(){
println("Welcome To My Domain this is the second example regarding the kotlin private constructor")
println("${this.stdid}")
println("${this.stdName}")
println("${this.stdRollno}")
println("${this.stdAddress}")
println("We have entered the student details like student id, student name, student roll number, student Address etc the information’s are encrypted and it is stored in the database server")
}
}
fun main(args: Array) {
var s = "Your companion object is called and used on this variable regarding the kotlin private constructor"
val ob=new1()
println(ob.exam())
println(ob.stddets())
println(s)
}

Output:

In the above example, we used a private constructor with the companion object to call the main method. We are unable to create the object for the private constructor.

Example #2

open class SecPrCon private constructor() {
fun example(): String {
return "Please enter your inputs"
}
companion object {
private var vars : SecPrCon? = null
fun getInstance(): SecPrCon {
if (vars == null) {
println("Please enter your valid inputs, still you are not entered valid inputs")
vars = SecPrCon()
println("Thank you users your inputs are successfully entered")
}
return vars as SecPrCon
}
}}
fun main(arg:Array)
{
println("Welcome To my Domain its the second example regarding the private constructor")
val bls = mutableListOf('j', 'u', 'n', 'e')
println(bls.binarySearch('u'))
bls.remove('e')
val sr = bls.binarySearch('u')
val cresult = -(sr + 1)
println(cresult)
bls.add(cresult, 'd')
println(bls)
data class eg(val st: String)
val va = listOf("J", "uly", "Month wise datas", "Please provide", "correct datas")
val qa = va.map { eg(it) }
val fnd = "eg"
val out = qa.binarySearch { String.CASE_INSENSITIVE_ORDER.compare(it.st, fnd) }
if (out >= 0) {
println("st at $out is ${qa[out]}")
} else {
println("eg with st=$fnd was not found in the data list please enter correct results")
}
}

Output:

In the second example, we used binary and heap sort, searching for the private constructor elements.

Example #3

Code:

import Third.Companion.tdemo
class Third private constructor() {
companion object {
fun tdemo() = Third()
}
}
class th1: Thread() {
public override fun run() {
println("Welcome Users the application runs now on ${Thread.currentThread()}")
}
}
class th2: Runnable {
public override fun run() {
println("Welcome Users the application runs now on ${Thread.currentThread()}")
}
}
fun main()
{
//val ins1 = Third()
val ins2 = tdemo()
println(ins2)
val thread = th1()
thread.start()
val runnable = th2()
val thread1 = Thread(runnable)
thread1.start()
}

Output:

In the final example, we used the multithread concept additionally, with the private constructor here, we can create the object by using the companion object for the private constructor class.

Conclusion

In kotlin, the constructor is important for object creation like that it has different types like public, default, and private constructors. The public is assigned for normal, and it can be used with all types of packages both internally and Externally. However, if we have not used constructor code takes default automatically; the private constructor cannot implement outside of the package.

Recommended Articles

This is a guide to Kotlin Private Constructor. Here we discuss How private constructor works in Kotlin and Examples along with the codes and outputs. You may also have a look at the following articles to learn more –

  1. Kotlin kclass
  2. Kotlin JSON
  3. Kotlin groupBy
  4. Kotlin Constructors

The post Kotlin private constructor appeared first on EDUCBA.



This post first appeared on Best Online Training & Video Courses | EduCBA, please read the originial post: here

Share the post

Kotlin private constructor

×

Subscribe to Best Online Training & Video Courses | Educba

Get updates delivered right to your inbox!

Thank you for your subscription

×