你的位置:首页 > Java教程

[Java教程]走进java对象的门口


从题目中可以看出来,今天只是java面向对象的入门级探讨。看看今天的内容。


 

为什仫说英语呢?我的英语从三年级都不好,一直到现在,但我们的未来职业要求我们必须懂英语,就算不能像马云一样溜吧,但最起码能看懂英语版的专业书籍。其实,专业上的英语挺简单的,如果你能静下心看看那些书,你会发现,书上的语法很简单,词汇还都是高中的,只有极个别的专业词汇有点难,记住就好啦,反正不多,所以,这里说几个英语名词。

面向对象三大特性:encapsulation:封装  inheritance:继承  polymorphism:多态

还有两个词用的比较多:arguments 和 parameters : 实参 和 形参。

编程语言的函数或方法都只能放回一个值(我只学过的几个,语言之多,不知有没有特例),有时想返回多个值,可以数组(当我刚学c语言的时候,我都不知道这样做),python好像能返回多个,直观上如此,但其实python返回的是一个元组,把你的多个返回值构成一个元组返回的。


一、封装

刚学面向对象时,对封装思想不甚了解,特别是从面向过程转过来的人。为什么要对属性进行封装呢?外部直接调用不是很方便吗?

其一原因:通过封装,外部只能通过你的getter() ,setter()来间接访问你的属性,那你不是可以在gette and setter 中做些什么了吗。比如:你写了个Person类,其中一个属性是年龄age,age的范围肯定是 age>= 0的(不知有没有长生的人),如果你不封装,外部可以把 -100 赋值给 age,显然这是不合理的,但通过setter来赋值时,你可以对传进的值进行判断如果小于 0,就抛个异常给调用者。是不是很好,通过封装你可以对传进的值进行一些判定或其他的操作啦。

你可能要反驳说啦,我见过一些setter or getter,就是最简单的赋值啊,没啥功能啊。下面就是另一个重要的使用封装的原因啦。

 

其二:The point to setters (and getters, too) is that you can change your mind later,without breaking anybody else’s code! 你写了个一款游戏,刚开始时你对游戏充钱的范围设置应该很低,假设充钱的下限是 一毛(哈哈),等过了一段时间,你的游戏大火,为了make more money,你要提高充钱的下限啦(反正总会有人充的,毕竟玩家多嘛),设为price >= 100。你想想,如果开发时你的公司员工都是把属性设置为public,如果想进行更改,你就的在原来需要给price赋值的地方做个if(money >= 100){//ok } else{//buy failure}判断,或者写setter(getter也一样),进行对传进的值判断,然后,在原来使用price的地方调用setter().看见了没有不用封装,以后想改都很麻烦,所以还是使用封装吧,别看现在可能没啥用,以后你有别的想法想改时,就很方便啦。记住这句话:you can change your mind later,without breaking anybody else’s code!


 

 插一段关于对象属性和局部变量初始值的问题:

 


 

二、“==”与equals方法的区别:

“==”比较的是两个变量在内存中的 bits 是否相等不关心你的类型是否相等,比如 int a = 1, b = 1; a == b //true  byte c = 1; a == c //also true,因为a,c在内存中的bits都是0000 0000 0000 0001。对于对象引用变量来书,他们比较是是否指向相同的对象,其实还是一样的,指向相同的对象,他们的bits就是相同的。所以,“==”,主要还是比较两个变量是否指向相同的对象(基本变量没啥好说的)。

有时,你不关心两个变量是否指向同一个对象,你只是关心两个变量指向的对象的内容是否完全一样。上代码,具体看看:

想想为什么.

再看一个对比的:

再猜猜结果:

奇妙的事情发生啦,str1 和 str2的值都是“hello",为什么他两相比的结果是false。因为,str1,str2指向的对象不同,虽然对象中的内容是相同的,但"=="只关心变量的二进制数是否相同,因为指向不同的对象,所以,他们之间的bits不可能相同。

那我想看两个字符串是否相同咋办?那就要用equals方法啦。

把判断语句稍微一改:

结果就是想要的啦:

记住这两句话:

Use == to compare two primitives, or to see if two references refer to the  same object.
Use the equals() method to see if two  different objects are equal.

 

留个问题,自己写个类,用“==” 和 equals()方法来比较一下,结果可能会出乎你的意料。具体如何,且看不知多少下回的分析。


When everything seems to be going against you, remember that the airplane takes off against the wind, not with it.

只有通过逆境,你才能变得强大。(我都被自己给翻译服啦,呵呵)

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIAAD/2wBDAA0JCgsKCA0LCgsODg0PEyAVExISEyccHhcgLikxMC4pLSwzOko+MzZGNywtQFdBRkxOUlNSMj5aYVpQYEpRUk//2wBDAQ4ODhMREyYVFSZPNS01T09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT0//wAARCADcANwDASIAAhEBAxEB/8QAGwABAAIDAQEAAAAAAAAAAAAAAAQFAQIDBgf/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