您的位置:首页 > 其它

面向对象复习一

2017-07-10 17:51 127 查看
一 万物皆对象

1.类是多组对象的相同信息的抽取,对象是类的实例化。例如:人类,就是所有人的对象的抽取,他们有相同的属性,名字,性别,年龄等等。

2.对象创建过程:new关键字 例如:People people=new People()

这句话所对应的内部操作:(1) 分配内存空间(堆中创建内存空间) (2) 初始化引用变量(People people) (3)调用构造方法(People类当中的构造方法) (4)返回实例对象的引用(将右边的new People() 与左边People people连接)

二 三大特性:封装,继承,多态

1.封装: 定义类,属性,方法的过程就是封装

2.目的:隐藏信息,向外部提供公开接口,安全调用

3.static 静态方法不能使用this关键字,只能调用静态成员(单例设计模式)

4.访问权限:大到小 public>protected>默认>private

public:(1)不同包,不是子类 (2)不同包,是子类 ,(3)同包类,(4)同类

protected (2)(3)(4) 默认 (3)(4) private (4)

5.方法重载与重写:

(1) 重写(overrride):用于继承中,子类重写父类的方法(方法名称,参数,返回值不改变) ,访问权限不能比父类更严格 ,父类私有方法,构造方法不能重写

(2) 重载:本类中,返回值,参数个数会发生改变,单有返回类型不同,访问修饰符不同,不是重载。注意:一定得有参数个数或类型发生改变。

6.this,super

this用于本类中,可以看作一个类类型的变量,构造方法时用到this.name=name;

super 在子类中调用父类方法和字段时用super关键字,子父类同名,可以用来区别,子类构造方法中用super继承父类构造

7.继承(extends)

子类拥与父类相同的属性和方法,便于节省代码,优化代码

子类不能继承父类的构造方法,私有方法,子类可以调用父类的构造方法,通过super 关键字

8.多态前提 存在继承实现关系 消除耦合

9.对象向上转型,丢失子类中非父类的方法(安全),向下转型(不安全 可能用到 instanceof 避免类转换异常)

例如:

public class DuoTaiDemo {

public static void main(String[] args) {
ColorPrinter cp=new ColorPrinter("zhangsan");
School school=new School();
school.setPrinter(cp);
school.daYin("nihao");

BlackPrinter bp=new BlackPrinter("lisi");
School school1=new School();
school1.setPrinter(bp);
school1.daYin("nihao");
}


}

class School{

private Printer printer=null;

/*public School(Printer printer){

this.printer=printer;

}*/

public void setPrinter(Printer printer){

this.printer=printer;//向上转型,调用子类中的重写父类的方法

}

public void daYin(String content){

printer.print(content);

}

}

class Printer{

private String pinPai;

public Printer(){}

public String getPinPai() {

return pinPai;

}

public void setPinPai(String pinPai) {

this.pinPai = pinPai;

}

public Printer(String pinPai){

this.pinPai=pinPai;

}

public void print(String content){}

}

class ColorPri
4000
nter extends Printer{

public ColorPrinter(String pinPai) {

super(pinPai);

}

public void print(String content){

System.out.println(getPinPai()+”彩色打印”+content);

}

}

class BlackPrinter extends Printer{

public BlackPrinter(String pinPai) {

super(pinPai);

}

public void print(String content){

System.out.println(getPinPai()+”黑白打印”+content);

}

}

上面例子就是动态绑定,用父类作为参数,当传子类参数时,自动向上转型,调用子类重写父类的打印方法,多态能优化代码,增加子类不用修改School类当中的内容,静态绑定,就是直接在方法上加static,直接用类名.方法调用,不用像动态绑定一样实例化,才能调用方法。

10.抽象类(abstract)与接口:

抽象类中可以有抽象方法,也可以没有,但有抽象方法一定是抽象类,抽象类不能实例化,不能被final修饰

抽象方法特点:没有方法体,有abstract修饰,不能被调用(is a)

接口(interface):接口只能存放静态常量和抽象方法,它避免了java不能多继承的缺点,接口之间可以extends联系 (like a)

一个类可以继承一个父类,实现多个接口

11.运行前后问题:

父类的静态成员赋值和静态块—>子类的静态成员和静态块—>父类的构造方法—>父类的成员赋值和初始化块—>父类的构造方法中的其它语句—>子类的成员赋值和初始化块—>子类的构造方法中的其它语句—>子类静态代码块—>父类构造方法—>子类构造—>子类方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: