这是本专栏的第二篇,记录我自学Berkeley CS 61B的笔记,作业等等。CS 61B作为CS入门的神课,会涉及到面向对象编程java和数据结构两方面的知识,笔者将会记录课程的关键知识,希望对你会有所帮助。
课程视频:https://www.bilibili.com/video/BV18x411L7yy
Professor:Jonathan Shewchuk
课程链接:https://people.eecs.berkeley.edu/~jrs/61b/
---------------------------这是分割线---------------------------
Lecture2 Defining Classes
Define a class
Feilds: Variables stored in an object, aka, instant variables.
eg: amanda.age -------- Field
amanda.introduce() ---- Method call
class definition 的例子
(如果是别的程序在用,不一定要有main method)
class Human{
public int age;
public String name;
// method definition
public void introduce(){
system.out.println("I'm" + name + "and I'm" + age + "years old.");
}
public void copy(Human original){
age = original.age;//不需要self.age,用了应该是this,结果也一样
this.name = original.name;
//用法:amanda.copy(rishi);
}
public Human(String givenName){
//这个的意思就是class的constructor永远叫一样的名字
//不写constructor的话也没关系,java会给你一个默认的constructor,没有参数,没有初始化
//public Human(){}就是这么一个函数,省的打印了
//age = 0/name = null
//自己构建了以后,default的constructor就没了
//如果想要default的constructor,必须自己写出来一个
age = 6;
name = givenName;
}
//重写default constructor:
public Human(){
age = 0;
name = "Untitled";
}
}
//用法
Human amanda = new Human();
amanda.age = 6;
amanda.name = "Amanda";
//or
Human amanda = new Human("Amanda");
amanda.introduce();
//output:
//I'm Amanda and I'm 6 years old
原理:
和之前讲的一样,都是先构建,再reference
这个int没有reference,因为他是primitive type(但是老师说也有专门的int class I 以后会讲)
The “this” keyword
amanda.introduce() implicitly passes an object (amanda) as a parameter called “this”
其实就是amanda和this都是variable,同时指向了上面的Human Object
图解:(其实我不是很懂这里) 查了一下就是this 和 amanda等价
class Human{
public int age;
public String name;
public void change(int age){
String name = "Tom";
//总之就是有混淆的话,用this特质我们这个class,如果没有混淆,就省略this
//右边是local variables,左边是field variables
this.age = age;
this.name = name;
}
}
amanda.change(11);
图解:
you cannot change the value of “this”
this = XXX; 报编译器错误
The “static” keyword
static field: a single variable shared by a whole class of objects
also called as class variables
System.in and System.out are static fields
Static method: doesn’t implicitly pass on object as a parameter. # 大概意思就是static method 跟object无关,每个object都是一样的。前面那个this的话,因为每个object不一样,所以要把object作为参数传进去。
main() is always static
in a static method, there is no “this” (compile-time error)
class Human{
public static int numberOfHumans;
public int age;
public String name;
public Human(){
numberOfHumans++;
}
public static void printHumans(){
System.out.println(numberOfHumans);
}
}
kids = Human.numberOfHumans/4;
转载:https://blog.csdn.net/Henry_Wang135/article/details/105738191