Monday 5 February 2018

Kotlin: Packages

Package is a name space that provides a way to organise interfaces, classes, functions in a way to avoid naming collisions.

Packages are like Directories. For Example, you can keep all the audio files in one directory, video files in other directory and text files in one directory. Similarly, A project can contain several files, so it is always good to organise them in consistent way. 

Benefits of Packages
1. Packages offers modularity, like we can logically group the things, for Example, all file related classes and interfaces can be in package named “file”, all the system related classes and interfaces in package named “system”, all the Graphical user interfaces classes can go to ‘userInterface’ package etc.,

2.We can apply access restrictions using access specifiers protected,private, internal and public.

3. Name Space Collisions avoided

4. Programmers or users can easily determine which classes are related based on package grouping

How to Create a Package
By using package keyword, you can define a package.

Syntax
package packageName;

for example, you can place all the data structure related classes and interfaces in package named ‘collections’.

Ex
package collections;

The package statement must be the first line in the source file.

How to create a package in Eclipse?
Right click on Kotlin project -> New -> Package
It opens below window, give the package name as ‘com.sample.model’.
Click on Finish button. You can see the updated project structure.
Define a class in the package ‘com.sample.model’
Right click on the package 'com.sample.model' -> New -> Other
Select Kotlin -> Kotlin Class
After that it opens a window, there give the class name as Employee and press Finish button.

How to import the package into other classes?
By using ‘import’ statement we can import other packages.

Ex
import com.sample.model.Employee

Find the below working application.

Employee.kt

package com.sample.model

class Employee {
 lateinit var firstName: String
 lateinit var lastName: String
 lateinit var id: String
}

HelloWorld.kt

import com.sample.model.Employee

fun main(args: Array<String>) {
 var obj = Employee()

 obj.firstName = "Chamu"
 obj.lastName = "Gurram"
 obj.id = "Id1234"

 println("First Name : ${obj.firstName}")
 println("Last Name : ${obj.lastName}")
 println("Id : ${obj.id}")

}

Output

First Name : Chamu
Last Name : Gurram
Id : Id1234


Previous                                                 Next                                                 Home

No comments:

Post a Comment