第二十二课 面向对象的基本概念(7)
来源:互联网 发布:管道45度的各种算法图 编辑:程序博客网 时间:2024/04/29 17:43
第二十二课 面向对象的基本概念(7)
一、 构造方法:与类名相同,一旦定义了构造方法,在对象被创建时就可自动调用,它完成对实例变量进行初始化。与一般方法不同的是,构造方法没有返回类型,它的返回类型是隐式的,就是类型本身。
比如:
public class Car{
public int gearNum;
public int engine;
Car(){
this.gearNum=0;
this.engine=0.0;
}
Car(int x,float y){
this.gearNum=x;
this.engine=y;
}
}
在上面的例子中我们定义了两个同名的构造函数,这就是“构造函数的重载”,这个我们以后还要继续讲。
如果我们在定义一个类时,没有定义和类同名的构造函数,JAVA内部也会生成一个默认的构造函数,但不进行任何操作。
二、 this和super的使用
我们来看一个例子:
public class Leaf{
private int i=0;
Leaf increment(){
i++;
return this;
}
void print(){
system.out.println(“I=”+i);
}
public static void main (string args[]){
Leaf x=new Leaf();
x.increment().increment().increment().print();
}
}
在上面的例子中,this返回的是当前对象的地址,所以可以方便地对同一个对象执行多项操作。
而super和this有着不同的概念,如果子类的对象想使用它父类中的同名属性和方法时,就可以使用了。
如下例:
public class WordTest{
int a;
WordTest(int a){
this.a=a;
}
WordTest(){
this(5);
}
}
public class SentenceTest extends WordTest{
int b;
SentenceTest{
super(3);
this.b=b;
}
}
在以上程序段中其实this(5)中的this就代表了本类中的第一个构造方法,而在super(3)中调用了父类的构造方法。另外要注意的是super关键字必须放在当前构造方法的第一行。
- 第二十二课 面向对象的基本概念(7)
- 第7课 面向对象的基本概念
- 面向对象的基本概念
- 面向对象的基本概念
- 面向对象的基本概念
- 面向对象的基本概念
- 面向对象的基本概念
- 面向对象的基本概念
- 面向对象的基本概念
- 面向对象的基本概念
- 面向对象的基本概念
- 面向对象的基本概念
- 面向对象的基本概念
- 面向对象的基本概念
- 面向对象的基本概念
- 面向对象的基本概念
- 面向对象的基本概念
- 面向对象的基本概念
- C 结构整体赋值给数组
- 第二十课 面向对象的基本概念(5)
- 企业管理技巧分享:六步轻松搞定子网划分
- 第二十一课 面向对象的基本概念(6)
- struts2入门的HelloWorld报错!
- 第二十二课 面向对象的基本概念(7)
- 第二十三课 面向对象的基本概念(8)
- WPF game developing 学习备注4--npc的问题
- 第二十四课 继承(1)
- IP地址合理分配
- 原生C#使用mask处理图片透明代码
- 用户控件(.ascx)与网页间(.aspx)如何传值的几种方法(持续更新)
- Linux下软件安装详解
- 用java实现cache