1.主构造器、构造器重载(辅助构造器)
package
com.jn.scala.oop
/**
* @author jiangning
*/
class
Student{
var
name
=
""
private
var
age
=
25
private
[
this
]
val
gender
=
"male"
//辅助构造器在最终形态上会调用主构造器
def
this
(
name
:
String
){
// 辅助构造器
this
()
//调用主构造器
this
.
name
=
name
}
def
this
(
name
:
String
,
age
: Int){
//辅助构造器
this
(
name
)
//调用有前一个辅助构造器
this
.
age
=
age
}
def
sayHello
(){
println
(
"name : "
+
this
.
name
+
" age :"
+
this
.
age
+
" gender : "
+
this
.
gender
)
}
}
object
OOPInScala
{
def
main
(
args
: Array[
String
]){
val
s1
=
new
Student()
s1
.
sayHello
()
val
s2
=
new
Student(
"Scala"
)
s2
.
sayHello
()
val
s3
=
new
Student(
"Scala"
,
5
)
s3
.
sayHello
()
}
}
//运行结果
name : age :25 gender : male
name : Scala age :25 gender : male
name : Scala age :5 gender : male
2.默认构造器
package
com.jn.scala.oop
/**
* @author jiangning
*/
class
Student(
val
name
:
String
,
val
age
: Int){
var
gender
:
String
= _
//一个占位符
//辅助构造器在最终形态上会调用主构造器
def
this
(
name
:
String
,
age
: Int,
gender
:
String
){
//辅助构造器
this
(
name
,
age
)
this
.
gender
=
gender
}
def
sayHello
(){
println
(
"name : "
+
this
.
name
+
" age :"
+
this
.
age
+
" gender : "
+
this
.
gender
)
}
}
object
OOPInScala
{
def
main
(
args
: Array[
String
]){
val
s1
=
new
Student(
"Scala"
,
5
)
s1
.
sayHello
()
val
s2
=
new
Student(
"Scala"
,
5
,
"male"
)
s2
.
sayHello
()
}
}
//运行结果
name : Scala age :5 gender : null
name : Scala age :5 gender : male
3.私有构造器
package
com.jn.scala.oop
/**
* @author jiangning
*/
class
Student
private
(
val
name
:
String
,
val
age
: Int){
var
gender
:
String
= _
//一个占位符
//辅助构造器在最终形态上会调用主构造器
def
this
(
name
:
String
,
age
: Int,
gender
:
String
){
//辅助构造器
this
(
name
,
age
)
this
.
gender
=
gender
}
def
sayHello
(){
println
(
"name : "
+
this
.
name
+
" age :"
+
this
.
age
+
" gender : "
+
this
.
gender
)
}
}
object
OOPInScala
{
def
main
(
args
: Array[
String
]){
// val s1 = new Student("Scala",5)//这里会报错
// s1.sayHello()
val
s2
=
new
Student(
"Scala"
,
5
,
"male"
)
//只能同过辅助构造器进行调用
s2
.
sayHello
()
}
}