当前位置: 首页 > 编程日记 > 正文

面向对象编程概念_如何向6岁的孩子解释面向对象的编程概念

面向对象编程概念

by Alexander Petkov

通过亚历山大·佩特科夫(Alexander Petkov)

Have you noticed how the same cliche questions always get asked at job interviews — over and over again?

您是否注意到在求职面试中总是一遍又一遍地问同样的陈词滥调问题?

I’m sure you know what I mean.

我确定你知道我的意思。

For example:

例如:

Where do you see yourself in five years?
五年后您在哪里看到自己?

or, even worse:

或更糟糕的是:

What do you consider to be your greatest weakness?
您认为什么是您最大的弱点?

Ugh…give me a break. I consider answering this question a great weakness! Anyway, not my point.

gh…给我休息一下。 我认为回答这个问题是一个很大的弱点! 无论如何,这不是我的意思。

As trivial as questions like these may be, they are important because they give clues about you. Your current state of mind, your attitude, your perspective.

尽管像这些问题一样琐碎,但它们很重要,因为它们为您提供了线索。 您当前的心态,态度和观点。

When answering, you should be careful, as you may reveal something you later regret.

在回答时,您应该小心,因为您可能会透露一些您以后会后悔的东西。

Today I want to talk about a similar type of question in the programming world:

今天,我想谈一谈编程世界中类似的问题:

What are the main principles of Object-Oriented Programming?
面向对象编程的主要原理是什么?

I’ve been on both sides of this question. It’s one of those topics that gets asked so often that you can’t allow yourself to not know.

我一直在这个问题的两面。 这是经常被问到的一些主题之一,以至于您无法让自己不知道。

Junior and entry-level developers usually have to answer it. Because it’s an easy way for the interviewer to tell three things:

初级和入门级开发人员通常必须回答。 因为这是面试官说出三件事的简单方法:

  1. Did the candidate prepare for this interview?

    候选人是否准备了这次面试?

    Bonus points if you hear an answer immediately — it shows a serious approach.

    如果您立即听到答案,将获得加分-这表明您是认真的方法。

  2. Is the candidate past the tutorial phase?

    候选人是否已超过辅导阶段?

    Understanding the principles of Object-Oriented Programming (OOP) shows you’ve gone beyond copy and pasting from tutorials — you already see things from a higher perspective.

    了解面向对象编程(OOP)的原理表明,您已经超出了教程中的复制和粘贴范围-您已经从更高的角度看到了事情。

  3. Is the candidate’s understanding deep or shallow?

    候选人的理解是深还是浅?

    The level of competence on this question often equals the level of competence on

    在这个问题上的能力水平通常等于在这个问题上的能力水平

    most other subjects. Trust me.

    其他大多数科目 。 相信我。

The four principles of object-oriented programming are encapsulation, abstraction, inheritance, and polymorphism.

面向对象程序设计的四个原则是封装抽象继承 多态性

These words may sound scary for a junior developer. And the complex, excessively long explanations in Wikipedia sometimes double the confusion.

对于初级开发人员来说,这些话听起来很吓人。 维基百科中复杂而冗长的解释有时会使混乱加倍。

That’s why I want to give a simple, short, and clear explanation for each of these concepts. It may sound like something you explain to a child, but I would actually love to hear these answers when I conduct an interview.

这就是为什么我要对每个概念进行简单,简短和清晰的解释。 听起来像是您向孩子解释的事情,但是当我进行面试时,我实际上很想听听这些答案。

封装形式 (Encapsulation)

Say we have a program. It has a few logically different objects which communicate with each other — according to the rules defined in the program.

说我们有一个程序。 根据程序中定义的规则,它具有几个逻辑上不同的对象,可以彼此通信。

Encapsulation is achieved when each object keeps its state private, inside a class. Other objects don’t have direct access to this state. Instead, they can only call a list of public functions — called methods.

当每个对象在类中保持其状态为private时 ,就可以实现封装。 其他对象没有直接访问此状态的权限。 取而代之的是,它们只能调用公共函数列表(称为方法)。

So, the object manages its own state via methods — and no other class can touch it unless explicitly allowed. If you want to communicate with the object, you should use the methods provided. But (by default), you can’t change the state.

因此,对象通过方法管理自己的状态-除非明确允许,否则其他任何类都不能接触它。 如果要与对象通信,则应使用提供的方法。 但是(默认情况下),您无法更改状态。

Let’s say we’re building a tiny Sims game. There are people and there is a cat. They communicate with each other. We want to apply encapsulation, so we encapsulate all “cat” logic into a Cat class. It may look like this:

假设我们正在构建一个小型的《模拟人生》游戏。 有人,有一只猫。 他们彼此交流。 我们要应用封装,因此我们将所有“ cat”逻辑封装到Cat 类。 它可能看起来像这样:

Here the “state” of the cat is the private variables mood, hungry and energy. It also has a private method meow(). It can call it whenever it wants, the other classes can’t tell the cat when to meow.

在这里,猫的“状态”是moodhungryenergy私人变量 。 它还有一个私有方法meow() 它可以随时调用它,其他类则不能告诉猫何时叫声。

What they can do is defined in the public methods sleep(), play() and feed(). Each of them modifies the internal state somehow and may invoke meow(). Thus, the binding between the private state and public methods is made.

它们可以做什么在公共方法 sleep()play()feed() 它们每个都以某种方式修改内部状态,并且可以调用meow() 因此,在私有国家和公共方法之间建立了约束。

This is encapsulation.

这是封装。

抽象化 (Abstraction)

Abstraction can be thought of as a natural extension of encapsulation.

抽象可以被认为是封装的自然扩展。

In object-oriented design, programs are often extremely large. And separate objects communicate with each other a lot. So maintaining a large codebase like this for years — with changes along the way — is difficult.

在面向对象的设计中,程序通常非常大。 并且单独的对象彼此之间经常进行通信。 因此,要像这样多年维护大型代码库(并不断进行更改)是很困难的。

Abstraction is a concept aiming to ease this problem.

抽象是旨在缓解此问题的概念。

Applying abstraction means that each object should only expose a high-level mechanism for using it.

应用抽象意味着每个对象应公开使用它的高级机制。

This mechanism should hide internal implementation details. It should only reveal operations relevant for the other objects.

此机制应隐藏内部实现细节。 它仅应显示与其他对象相关的操作。

Think — a coffee machine. It does a lot of stuff and makes quirky noises under the hood. But all you have to do is put in coffee and press a button.

想想-咖啡机。 它做很多事情,在引擎盖下发出古怪的声音。 但是,您所要做的只是喝咖啡并按下一个按钮。

Preferably, this mechanism should be easy to use and should rarely change over time. Think of it as a small set of public methods which any other class can call without “knowing” how they work.

优选地,该机制应该易于使用并且应该很少随时间变化。 可以将其视为少量的公共方法,任何其他类都可以在不“知道”它们如何工作的情况下调用它们。

Another real-life example of abstraction? Think about how you use your phone:

另一个现实生活中的抽象示例? 考虑一下如何使用手机:

You interact with your phone by using only a few buttons. What’s going on under the hood? You don’t have to know — implementation details are hidden. You only need to know a short set of actions.

您只需使用几个按钮即可与手机互动。 到底发生了什么事? 您不必知道-实施细节被隐藏。 您只需要知道一些简短的操作即可。

Implementation changes — for example, a software update — rarely affect the abstraction you use.

实现更改(例如,软件更新)很少影响您使用的抽象。

遗产 (Inheritance)

OK, we saw how encapsulation and abstraction can help us develop and maintain a big codebase.

好的,我们看到了封装和抽象如何帮助我们开发和维护大型代码库。

But do you know what is another common problem in OOP design?

但是您知道OOP设计中的另一个常见问题是什么吗?

Objects are often very similar. They share common logic. But they’re not entirely the same. Ugh…

对象通常非常相似。 他们有着共同的逻辑。 但他们不完全一样。 啊…

So how do we reuse the common logic and extract the unique logic into a separate class? One way to achieve this is inheritance.

那么,我们如何重用通用逻辑并将独特逻辑提取到单独的类中呢? 实现此目的的一种方法是继承。

It means that you create a (child) class by deriving from another (parent) class. This way, we form a hierarchy.

这意味着您通过派生另一个(父)类来创建(子)类。 这样,我们形成了一个层次结构。

The child class reuses all fields and methods of the parent class (common part) and can implement its own (unique part).

子类重用父类的所有字段和方法(公共部分),并可以实现其自己的(唯一部分)。

For example:

例如:

If our program needs to manage public and private teachers, but also other types of people like students, we can implement this class hierarchy.

如果我们的计划需要管理公共和私人教师,还需要管理其他类型的人(如学生),我们可以实施此类班级结构。

This way, each class adds only what is necessary for it while reusing common logic with the parent classes.

这样,每个类在重复使用父类的通用逻辑的同时,仅添加必要的内容。

多态性 (Polymorphism)

We’re down to the most complex word! Polymorphism means “many shapes” in Greek.

我们只能说最复杂的词了! 多态性在希腊语中意为“许多形状”。

So we already know the power of inheritance and happily use it. But there comes this problem.

因此,我们已经知道继承的力量并乐于使用它。 但是出现了这个问题。

Say we have a parent class and a few child classes which inherit from it. Sometimes we want to use a collection — for example a list — which contains a mix of all these classes. Or we have a method implemented for the parent class — but we’d like to use it for the children, too.

假设我们有一个父类和一些继承自它的子类。 有时我们想使用一个集合(例如一个列表),其中包含所有这些类的混合。 或者我们为父类实现了一个方法-但我们也想将其用于子类。

This can be solved by using polymorphism.

这可以通过使用多态来解决。

Simply put, polymorphism gives a way to use a class exactly like its parent so there’s no confusion with mixing types. But each child class keeps its own methods as they are.

简而言之,多态为使用类提供了一种完全类似于其父类的方法,因此不会与混合类型混淆。 但是每个子类都按原样保留自己的方法。

This typically happens by defining a (parent) interface to be reused. It outlines a bunch of common methods. Then, each child class implements its own version of these methods.

这通常是通过定义要重用的(父)接口来发生的。 它概述了一堆常用方法。 然后,每个子类实现这些方法的自己的版本。

Any time a collection (such as a list) or a method expects an instance of the parent (where common methods are outlined), the language takes care of evaluating the right implementation of the common method — regardless of which child is passed.

每当集合(例如列表)或方法需要父级实例(概述了通用方法)时,该语言都会负责评估通用方法的正确实现-不管传递哪个子级。

Take a look at a sketch of geometric figures implementation. They reuse a common interface for calculating surface area and perimeter:

看一下几何图形实现的草图。 它们重用了一个公共接口来计算表面积和周长:

Having these three figures inheriting the parent Figure Interface lets you create a list of mixed triangles, circles, and rectangles. And treat them like the same type of object.

通过使这三个图形继承父Figure Interface ,可以创建混合trianglescirclesrectangles 。 并将它们视为相同类型的对象。

Then, if this list attempts to calculate the surface for an element, the correct method is found and executed. If the element is a triangle, triangle’s CalculateSurface() is called. If it’s a circle — then cirlce’s CalculateSurface() is called. And so on.

然后,如果此列表尝试计算元素的曲面,则会找到并执行正确的方法。 如果元素是三角形,则三角形的CalculateSurface() 叫做。 如果是圆,则为cirlce的CalculateSurface() 叫做。 等等。

If you have a function which operates with a figure by using its parameter, you don’t have to define it three times — once for a triangle, a circle, and a rectangle.

如果您有一个通过使用图形的参数来处理图形的函数,则不必定义3次-一次定义一个三角形,一个圆形和一个矩形。

You can define it once and accept a Figure as an argument. Whether you pass a triangle, circle or a rectangle — as long as they implement CalculateParamter(), their type doesn’t matter.

您可以定义一次并接受一个Figure 作为争论。 传递三角形,圆形还是矩形-只要它们实现CalculateParamter() ,它们的类型就无关紧要。

I hope this helped. You can directly use these exact same explanations at job interviews.

希望对您有所帮助。 您可以在面试中直接使用这些完全相同的解释。

If you find something still difficult to understand — don’t hesitate to ask in the comments below.

如果您发现仍然难以理解的内容,请随时在下面的评论中提问。

下一步是什么? (What’s next?)

Being prepared to answer one of the all-time interview question classics is great — but sometimes you never get called for an interview.

准备回答一个经典的面试问题真是太好了,但是有时候您从没有被要求面试。

Next, I’ll focus on what employers want to see in a junior developer and how to stand out from the crowd when job hunting.

接下来,我将重点介绍雇主希望在初级开发人员中看到的东西,以及在求职时如何脱颖而出。

Stay tuned.

敬请关注。

翻译自: https://www.freecodecamp.org/news/object-oriented-programming-concepts-21bb035f7260/

面向对象编程概念

相关文章:

jQuery 属性

jQuery 属性 方法描述context在版本 1.10 中被废弃。包含被传递到 jQuery 的原始上下文jquery包含 jQuery 的版本号jQuery.fx.interval改变以毫秒计的动画运行速率jQuery.fx.off对所有动画进行全局禁用或启用jQuery.support包含表示不同浏览器特性或漏洞的属性集(主…

mongodb的几种启动方法

1 mongodb的几种启动方法 启动Mongodb服务有两种方式,前台启动或者Daemon方式启动,前者启动会需要保持当前Session不能被关闭,后者可以作为系统的fork进程执行,下文中的path是mongodb部署的实际地址。1. 最简单的启动方式&#xf…

php 修改数据库表的字段的值

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 php 前端传递参数&#xff0c;遍历数据库表的字段后根据条件进行修改。 <?phpheader("Content-Type:text/html;charsetutf8"); header("Access-Control-Allow-Origin: *"); //解…

如何开始使用PostgreSQL

by Akul Tomar通过Akul Tomar 如何开始使用PostgreSQL (How to get started with PostgreSQL) PostgreSQL is an open source Relational Database Management System (RDBMS). In this article, I’ll provide an introduction to getting started with PostgreSQL. Here is …

Java中数组常见的几种排序方法!

数组的定义&#xff1a; int[] arr new int[5];int[] arr1 {1,2,3,4,5};long[] arr2 new long[6];String[] strs new String[5];Person[] ps new Person[5]; 数组的操作&#xff1a; int[] arr {45, 34, 53, 43};Arrays.sort(arr);System.out.println(Arrays.toString(ar…

oracle 如何预估将要创建的索引的大小

一.1 oracle 如何预估将要创建的索引的大小 oracle 提供了2种可以预估将要创建的索引大小的办法&#xff1a; ① 利用包 Dbms_space.create_index_cost 直接得到 ② 利用11g新特性 Note raised when explain plan for create index 下边分别举例说明。 一.2 环境说明 [ora…

删除对象的某个属性

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 实现代码&#xff1a; var data {a:1,b:2,c:3}for(var item in data){if (item b) {delete data[item];} }console.log(data:, data) 打印结果&#xff1a; data: {a: 1, c: 3}

java 学到什么实习_我如何获得外展实习机会以及到目前为止所学到的知识

java 学到什么实习by Nguedia Adele由Nguedia Adele 我如何获得外展实习机会以及到目前为止所学到的知识 (How I got my Outreachy internship and what I’ve learned so far) I recently got accepted for an Outreachy internship, working with LibreHealth.我最近接受了与…

STM32F103C8开发板原理图和管脚图

转载于:https://www.cnblogs.com/libra13179/p/6894335.html

js实用数组方法

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 判断是否为数组 1. Array.isArray([]) 2. var arr[1,2] arr instanceof Array -->true arr instanceof String -->false map ---- 返回数组得出的结果 const filtered [1, 2,…

BasicModal - 简单易用的现代 Web App 弹窗

BasicModal 是为现代 Web 应用程序打造的弹窗系统。它包括所有你需要显示的信息&#xff0c;问题或接收用户的输入。这里的弹窗还可以链接起来&#xff0c;所以你可以很容易地建立一个预定义顺序的安装帮助或显示对话框。无效输入可以使用包含突出显示和处理功能。 在线演示 …

javascript选择器_如何通过选择正确JavaScript选择器来避免沮丧

javascript选择器选择器如何影响代码的快速指南 (A quick guide on how selectors affect your code) While working on a project, I ran into an issue in my code. I was attempting to define multiple HTML elements into a collection and then change those elements ba…

Asp.net中GridView使用详解(引)【转】

Asp.net中GridView使用详解(引) GridView无代码分页排序 GridView选中&#xff0c;编辑&#xff0c;取消&#xff0c;删除 GridView正反双向排序 GridView和下拉菜单DropDownList结合 GridView和CheckBox结合 鼠标移到GridView某一行时改变该行的背景色方法一 鼠标移到GridView…

《任正非:我若贪生怕死,何来让你们英勇奋斗》

非常高兴尼泊尔代表处的进步&#xff0c;你们的一个历史项目概算亏损&#xff0c;从大前年亏损2.7亿美金&#xff0c;到前年亏损3000万美金&#xff0c;到去年盈利2140万美金。在喜马拉雅南麓一路爬坡&#xff0c;辛苦了。听说去年你们都涨了工资&#xff0c;我十分高兴。巴西代…

个人使用微信支付

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 首先在PAYJS申请到商户号和密钥&#xff0c; 然后实现源码如下&#xff1a; <!DOCTYPE html> <html lang"zh"><head><meta charset"UTF-8"><title>…

构建node.js基础镜像_我如何使用Node.js构建工作抓取网络应用

构建node.js基础镜像by Oyetoke Tobi Emmanuel由Oyetoke Tobi Emmanuel 我如何使用Node.js构建工作抓取网络应用 (How I built a job scraping web app using Node.js) Scraping jobs from the web has now become easier thanks to Indreed.现在&#xff0c;借助Indreed&…

Robotium测试报告的生成方法(上)

7.1 使用junit-report生成报告 这个是参考网上的&#xff1a;http://www.xuebuyuan.com/2148574.html&#xff0c;经我个人验证是可行的方法&#xff0c;网上写的挺详细的&#xff0c;不过有些不太清楚明白的地方&#xff0c;鉴于网上说的有点迷茫&#xff0c;所以下面我再细化…

Python之向日志输出中添加上下文信息

除了传递给日志记录函数的参数&#xff08;如msg&#xff09;外&#xff0c;有时候我们还想在日志输出中包含一些额外的上下文信息。比如&#xff0c;在一个网络应用中&#xff0c;可能希望在日志中记录客户端的特定信息&#xff0c;如&#xff1a;远程客户端的IP地址和用户名。…

小程序点击图片自动播放视频,停止上一个视频播放

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 通过列表的点击事件自动播放列表对应的视频&#xff0c;同时停止上一个视频的播放 源码&#xff1a; <view><view classvv wx:for{{vedio_data}} wx:key><view classblock stylemargin…

hitchhiker部署_Hitchhiker的React Router v4指南:无限远的递归路径!

hitchhiker部署Welcome to the third part of the Hitchhiker’s Guide to React Router v4. In this article we’re going to focus on recursive paths. If you’ve missed the first two parts, you can find part 1 here and part 2 here.欢迎阅读《 Hitchhiker React Rou…

smbpasswd 和 pdbedit 的区别

smbpasswd 和 pdbedit 的区别 以前我们在windows上共享文件的话&#xff0c;只需右击要共享的文件夹然后选择共享相关的选项设置即可。然而如何实现windows和linux的文件共享呢&#xff1f;这就涉及到了samba服务了&#xff0c;这个软件配置起来也不难&#xff0c;使用也非常简…

DB天气app冲刺二阶段第十一天(完结)

今天最后一天冲刺了&#xff0c;明天就不再冲刺了。。已经把所有的技术的问题还有设计的问题都弄好了吧应该说 至少目前来说是的。因为有的实现不了的或者需要耗费时间的已经果断舍弃了&#xff0c;然后需要完善的也都基本完善了。 现在还需要做的就是素材的收集整理。需要抽半…

如何超越console.log并充分利用浏览器的调试控制台

by Gilad Dayagi通过吉拉德达亚吉 The console object is a very useful feature of browsers that has been around for many years. It provides access to the browser’s debugging console.Most web developers know how to print messages to the console using console…

区域设置 ID (LCID) 表, 及获取方法

区域设置 ID (LCID) 表, 及获取方法 中国的区域设置 ID 是 2052, 如果经常打开微软软件的安装目录应该经常见到.获取很简单, 有现成的 API 函数: GetThreadLocale.beginShowMessage(IntToStr(GetThreadLocale)); //2052 end; 区域设置 ID (LCID) 表区域设置描述简写十六进制值十…

E201700525-hm

skeleton n. 骨骼; &#xff08;建筑物等的&#xff09; 骨架; 梗概; 骨瘦如柴的人&#xff08;或动物&#xff09;;adj. 骨骼的; 骨瘦如柴的; 概略的; 基本的; cloud n. 云; 云状物; invoke vt. 乞灵&#xff0c;祈求; 提出或授引…以支持或证明; 召鬼; 借助;render …

php不显示报错

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 error_reporting(E_ALL & ~E_NOTICE);

致谢 开源开发者的贡献_对开源做出的贡献如何使我成为更好的开发人员,以及如何做到这一点...

致谢 开源开发者的贡献by Luciano Strika通过卢西亚诺斯特里卡(Luciano Strika) 对开源做出的贡献如何使我成为更好的开发人员&#xff0c;以及如何做到这一点 (How contributing to open source made me a better developer — and how you can do it, too) So you’ve been …

欲精一行,必先通十行

将前端开发和服务器端开发做一个比较&#xff0c;前端开发没有服务器端开发“深”&#xff0c;服务器端开发没有前端开发“广”。经常听到做前端的同行抱怨需要学的东西太 多&#xff0c;东学一点西学一点&#xff0c;什么都会&#xff0c;但也什么都不精。很直接的结果就是沦为…

LeetCode 228: Summary Ranges

Given a sorted integer array without duplicates, return the summary of its ranges. For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"]. 代码要求对数组中的元素进行分段。 首先给出字符串格式化函数&#xff0c;假设be…

JQ+ajax 提交表单不跳转页面

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 代码 <div class"apply_box"><h1>合作申请</h1><div class"apply_l"><input type"text" maxlength"20" id"name" name&q…