Kotlin constructors (#4933)
This commit is contained in:
parent
570e33dc1a
commit
4cd349f533
17
core-kotlin/src/main/java/com/baeldung/constructor/Car.kt
Normal file
17
core-kotlin/src/main/java/com/baeldung/constructor/Car.kt
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
package com.baeldung.constructor
|
||||||
|
|
||||||
|
class Car {
|
||||||
|
val id: String
|
||||||
|
val type: String
|
||||||
|
|
||||||
|
constructor(id: String, type: String) {
|
||||||
|
this.id = id
|
||||||
|
this.type = type
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
fun main(args: Array<String>) {
|
||||||
|
val car = Car("1", "sport")
|
||||||
|
val s= Car("2", "suv")
|
||||||
|
}
|
@ -0,0 +1,3 @@
|
|||||||
|
package com.baeldung.constructor
|
||||||
|
|
||||||
|
class Employee(name: String, val salary: Int): Person(name)
|
@ -0,0 +1,19 @@
|
|||||||
|
package com.baeldung.constructor;
|
||||||
|
|
||||||
|
class PersonJava {
|
||||||
|
final String name;
|
||||||
|
final String surname;
|
||||||
|
final Integer age;
|
||||||
|
|
||||||
|
public PersonJava(String name, String surname) {
|
||||||
|
this.name = name;
|
||||||
|
this.surname = surname;
|
||||||
|
this.age = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public PersonJava(String name, String surname, Integer age) {
|
||||||
|
this.name = name;
|
||||||
|
this.surname = surname;
|
||||||
|
this.age = age;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,26 @@
|
|||||||
|
package com.baeldung.constructor
|
||||||
|
|
||||||
|
open class Person(
|
||||||
|
val name: String,
|
||||||
|
val age: Int? = null
|
||||||
|
) {
|
||||||
|
val upperCaseName: String = name.toUpperCase()
|
||||||
|
|
||||||
|
init {
|
||||||
|
println("Hello, I'm $name")
|
||||||
|
|
||||||
|
if (age != null && age < 0) {
|
||||||
|
throw IllegalArgumentException("Age cannot be less than zero!")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
init {
|
||||||
|
println("upperCaseName is $upperCaseName")
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
fun main(args: Array<String>) {
|
||||||
|
val person = Person("John")
|
||||||
|
val personWithAge = Person("John", 22)
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user