这是一个新的专栏,记录我自学Berkeley CS 61B的笔记,作业等等。CS 61B作为CS入门的神课,会涉及到面向对象编程java和数据结构两方面的知识,笔者将会记录课程的关键知识,希望对你会有所帮助。
课程视频:https://www.bilibili.com/video/BV18x411L7yy
Professor:Jonathan Shewchuk
课程链接:https://people.eecs.berkeley.edu/~jrs/61b/
---------------------------这是分割线---------------------------
Lecture1 Course overview, Using objects
文章目录
Goals of CS 61B
- Learning efficient data structures and algorithms
- Designing and writing large programs
- Understanding and designing data abstraction and interfaces
- Learning java
Object Oriented Programming 概述
Object: A repository of data
Class: Type of object
Method: A class may inherit properties from a more general class
eg: ShoppingList inherits from List the property of storing a sequence of items.
Polymorphism: One method works on several classes, even if the classes need different implementations
eg: “addItem” method to every kind of list, although adding item to a shopping list is different from a shopping cart.
Objected-Oriented: Each object knows its class and methods
java对object的引用
Java在声明一个Object(如String)的时候,会构建一个Variable,这个Variable实际上有点类似于C++的指针,或者叫reference,他是会指向一个String Object,但是他本身并不是一个String Object,而只是一个指向String的Variable。
例如:
String myString;
myString = new String();
这里的new String()实际上就是构建了一个空的String Object,赋值的过程就是将myString指向了这个Object
如果没有第二行的话,myString就是一个null pointer,也就是指向nothing。
All “null” pointer don’t point to anything, they all point to the same “Nothing”.
如图:
再例如:
String s = new String();
s = "Yow!"
实际上,在进行s = “Yow!” 的操作的时候,java不会改变刚才那个空Object的结果,实际上,Java做的是重新生成了一个Object,这个Object的内容是“Yow!”,然后将s重新赋值到这个新的Object上。
如图:
再来几个例子:
String s = new String();
System.out.println(System.identityHashCode(s));
s = "Yow!";
System.out.println(System.identityHashCode(s));
String s2 = s;
System.out.println(System.identityHashCode(s2));
String s3 = "Yow!";
System.out.println(System.identityHashCode(s3));
String s4 = new String(s);
System.out.println(System.identityHashCode(s4));
把这几个的地址输出,得到
789451787
1950409828
1950409828
1950409828
1229416514
我们可以发现对于s2 s3的用法,都指向了原来的s,只有s4的用法才是构建了一个新的Object,可以说是非常节省内存了。用示意图来表示就是这样:
这种方式还有另外一个好处,就是当s和s2同时指向同样一个Object的时候,s的改变仅仅就是s指向了另外一个Object,对s2毫无影响。
另外,当没有任何Variable指向某个Object的时候,java会有一个garbage collector,回收掉这部分的内存。