------- android培训、java培训、期待与您交流! ----------
面向对象编程工作原理
用Java创建的程序可以看作一个对象,如同真实世界中存在的物体一样。对象独立于其他的对象而存在并且以特定的方式同其他的对象进行交互,从而合并成更大的事务。将计算机程序视为一组彼此交互的对象,这样设计出来的程序更可靠,更容易理解,更容易在其他的项目中重用。
在面向对象编程中,对象包含两项内容:属性和行为。其中,属性描述对象并使其不同于其他对象,而行为指的是对象能做什么。
面向对象的特征
- 封装(Encapsulation)
定义:封装是指隐藏对象的属性和实现细节,仅对外提供 公共访问方式。
优点:将变化隔离、便于使用、提高重用性、提高安全性。
原则:将不需要对外提供的内容都隐藏起来、把属性都隐藏,提供公共方法对其访问。
- 继承(Inheritance)
定义:面向对象允许一个对象继承另外一个对象的行为和属性。
优点:通过继承,我们无需做大量重复的工作就可以开发大量相关的类,它使得代码可以从一个类传递给另一个类,再传递给其他的类。这为多态性提供了前提。
- 多态(Polymorphism)
定义:某一类事物的多种存在形态。
优点:多态的存在提高了程序的扩展性和后期可维护性。
原则:需要存在继承或者实现关系
构造函数
- 特点
1.函数名与类名相同
2.不用定义返回值类型
3.不能写return语句
- 作用
建立对象时会调用对应的构造函数将对象进行初始化
对象的创建实例
下面通过一个关于类和继承的例子,以加强对面向对象思想的理解:
输出结果如下:package com.itheima; /** * 通过实例加深对面向对象思想的理解 * @author Ryan */ public class StudentTest { /** * @param args */ public static void main(String[] args) { StudentTest.GoodStudent gs = new StudentTest.GoodStudent(); //创建两个新对象,一个是名为gs的GoodStudent对象 StudentTest.BadStudent bs = new StudentTest.BadStudent(); //另一个是名为bs的BadStudent对象 gs.score = 100; bs.score = 60; System.out.println("Here's the good student:"); gs.introduce(); //调用gs对象的introduce()方法 gs.displayScore();//调用gs对象的displayScore()方法,该方法是从Student类中继承的,虽然GoodStudent类中没有,但也可以调用 System.out.println("Here's the bad student:"); bs.introduce(); bs.displayScore(); } public static class Student { int score; //每个对象都有考试分数 //定义一个displayScore方法用以继承 public void displayScore() { System.out.println("I aways got "+score+" scores in examinations.\""); } } //定义一个继承Student类的GoodStudent类 public static class GoodStudent extends Student { String grade = "\"I'm a good student!"; public void introduce() { System.out.println(grade); } } //定义一个继承Student类的BadStudent类 public static class BadStudent extends Student { String grade = "\"I'm a bad student..."; public void introduce() { System.out.println(grade); } } }
Here's the good student:
"I'm a good student!
I aways got 100 scores in examinations."
Here's the bad student:
"I'm a bad student...
I aways got 60 scores in examinations."