您的位置:首页 > 编程语言 > Java开发

java继承、多态基础

2016-01-04 15:34 423 查看
面向对象编程的主要特点有四个:继承、多态、抽象、封装;

封装:封装是面向对象的特征之一,是对象和类概念的主要特性。封装是把过程和数据包围起来,对数据的访问只能通过已定义的界面。面向对象计算始于这个基本概念,即现实世界可以被描绘成一系列完全自治、封装的对象,这些对象通过一个受保护的接口访问其他对象。一旦定义了一个对象的特性,则有必要决定这些特性的可见性,即哪些特性对外部世界是可见的,哪些特性用于表示内部状态。在这个阶段定义对象的接口

继承:继承是一种联结类的层次模型,并且允许和鼓励类的重用,它提供了一种明确表述共性的方法。对象的一个新类可以从现有的类中派生,这个过程称为类继承。新类继承了原始类的特性,新类称为原始类的派生类(子类),而原始类称为新类的基类(父类)。派生类可以从它的基类那里继承方法和实例变量,并且类可以修改或增加新的方法使之更适合特殊的需要。

多态:多态性是指允许不同类的对象对同一消息作出响应

抽象:抽象就是忽略一个主题中与当前目标无关的那些方面,以便更充分地注意与当前目标有关的方面。抽象并不打算了解全部问题,而只是选择其中的一部分,暂时不用部分细节

public class test {
class A{
public String show(D obj){
return ("A and D");
}
public String show(A obj){
return ("A and A");
}

public String printString(){
return "A";
}
}
class B extends A{
public String show(B obj){
return ("B and B");
}
public String show(A obj){
return ("B and A");
}
public String printString(){
return "AB";
}
}
class C extends B{}
class D extends B{}
class E extends A{
public String show(B obj){
return ("E and B");
}
public String show(A obj){
return ("E and A");
}
public String printString(){
return "AE";
}
}

public static void main(String[] args) {
// TODO Auto-generated method stub
//多态(A、B、E不同对象调用了A的同一个方法,执行结果不同)
A a1 = new test().new A();
A a2 = new test().new B();
A a3 = new test().new E();
System.out.println(a1.printString());
System.out.println(a2.printString());
System.out.println(a3.printString());
//继承(输出结果是:A and A
A and A
A and D
B and A
B and A
A and D
B and B
B and B
A and D)
// A a1 = new test().new A();
// A a2 = new test().new B();
// B b = new test().new B();
// C c = new test().new C();
// D d = new test().new D();
// System.out.println(a1.show(b));
// System.out.println(a1.show(c));
// System.out.println(a1.show(d));
// System.out.println(a2.show(b));
// System.out.println(a2.show(c));
// System.out.println(a2.show(d));
// System.out.println(b.show(b));
// System.out.println(b.show(c));
// System.out.println(b.show(d));
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: