- java类的设计,其实就是设计类的成员
属性 = 成员变量 = field = 域、字段
方法 = 成员方法 = method = 函数
创建类的对象 = 类的实例化 = 实例化类
- 类和对象的使用
-
先创建类,并设计类的成员
-
创建类的对象
-
通过
“对象.属性” 或 “对象.方法”
调用对象的结构public class test { public static void main(String[] args){ Person p1 = new Person(); p1.name = "faker"; System.out.println(p1.name); p1.eat(); p1.talk("中国"); } } class Person{ //属性 String name; int age = 1; boolean isMale; //方法 public void eat(){ System.out.println("人不能不吃饭"); } public void talk(String words){ System.out.println("我们非常热爱" + words); } }
- 如果创建了一个类的多个对象,则每个对象都独立的拥有一套类的属性(非static的)
如果我们修改了一个类的对象fish的属性a,则不影响另一个类的对象tiger的属性a
-
对象的内存解析
-
堆
此区域基本存在的唯一目的就是存放对象实例,如我new了一个对象p1,p1的实际数据就存放在这里
-
栈
主要存储局部变量
含对象引用(对象的指针),各种基本数据类型等
方法执行完,自动释放。
- 方法区
-
-
在类中创建数组的注意事项
类class中创建数组并未初始化时,在另一个地方调用时,一定要初始化即new一下。
当然也不管是类本身的数组,还是在类中其他数组,只要在类中未初始化,调用前都要new一下
如果是创建的类的数组,在使用某一个类时要先new一下,如下
public class practise { public static void main(String[] args){ Student []stus1 = new Student[5]; //在这加个stus1[0] = new Student();即可 stus1[0].num = 1; //在使用之前应先new个stus1[0],不然里面是NULL System.out.println(stus1[0].num); } } class Student{ int num; }
报错:
Exception in thread “main” java.lang.NullPointerException
at praticses.practise.main(practise.java:6) -
类new后如果直接打印显示其地址值,且可以赋值null
public class practise { public static void main(String[] args){ Student stus1 = new Student(); Student stus2 = new Student(); stus2 = null; System.out.println(stus1); System.out.println(stus2); } } class Student{ }
输出:
praticses.Student@15db9742
null