1. 对象的创建和使用
必须使用new关键字 + 构造方法创建对象。
使用对象.成员变量来引用对象的成员变量。 circle1.radius
使用对象.方法名(实参列表)来调用对象的方法。circle1.getArea()
2. 使用构造方法构造对象
1) 必须具备和所在类相同的名字;
2) 没有返回类型;
3) 定义在Java类中的一个用来初始化对象的函数;
class Person{ //Person类的构造函数
int id;
int age;
Person(int n,int i){
id = n;
age = i;
}
}
4) 创建对象时,使用构造函数初始化对象的成员变量;
public class Test1{
public static void main(String[] args){
Person tom = new Person(1,25);
Person jack = new Person(2,30);
}
}
3. 创建一个类包括数据域(成员变量)、构造函数、方法
4. 引用数据域和null值
1)给局部变量赋值
class Student{
int name;
int age;
Student (int n,int a){
name = n;
age = a;
}
}
public class TestStudent{
public static void main(String[] args){
Student student = new Student(2,3);
System.out.println("name? " + student.name + "age? " + student.age);
}
}
2)不给局部变量赋值
class Student{
int name;
int age;
Student ( ){
}
}
public class TestStudent{
public static void main(String[] args){
Student student = new Student( );
System.out.println("name? " + student.name + "age? " + student.age);
}
}
5. 基本类型和引用类型
每个变量都代表一个存储的内存位置。
基本类型:对应内存所存储的值是基本类型;
引用类型:对应内存所存储的值是一个引用,是对象的存储地址。
Class objectRefVar; 类名 对象引用变量;
变量objectRefVar 引用一个Class 对象;
例: Circle c 对象c的值存的是一个引用,c 为一个引用变量,指明这个Circle对象的内容存储在内存中的位置。