类是自定义的数据类型,对象是类的实例

养猫问题,存储两只猫的信息
public class Object {
public static void main(String[] args) {
// 实例化猫
Cat cat1 = new Cat();
cat1.age = 3;
cat1.name = "小白";
cat1.color = "白色";
Cat cat2 = new Cat();
cat2.age = 100;
cat2.name = "小花";
cat2.color = "花色";
}
}
//创建猫类
class Cat {
String name;
int age;
String color;
}

class Cat {}
Cat cat
cat = new Cat();
// 可以和第二步直接结合
Cat cat = new Cat();
cat.age
cat.color

执行main函数时会先开辟出一个main栈,开始执行main函数
在main栈中先执行new语句在堆中来开辟一处空间
然后调用函数,会在主栈中在开辟一个getsum栈,函数执行完毕后该栈自动销毁

允许在同一个类中多个同名方法存在,但要求形参不一样。
class Computed {
public int calculate(int a, int b) {
return a + b;
}
public double calculate(int a, double b) {
return a + b;
}
public double calculate(double a, int b) {
return a + b;
}
public int calculate(int a, int b, int c){
return a + b + c;
}
}
将同一个类中多个同名同功能的但参数个数不同的方法封装成一个方法。
类似ES6的剩余参数
class HspMethod {
//int... 表示接受的是可变参数(可以接受0-n的整数)
//传入的参数会被存储在numbers数组中
public int sum(int... numbers) {
int t = 0;
for (int i = 0; i < numbers.length; i++) {
t += numbers[i];
}
return t;
}
}
class T {
int age;
char sex;
T (int a,char b){
age = a;
sex = b;
}
}
this的本质就是一个指向自身的属性,简单来说,哪个对象调用,this就代表哪个对象。
