类的定义-对象的创建使用
类的定义
事务与类的对比
现实世界 的一类事物:
属性:事物的状态信息.行为:事务能够做什么.
java中用class描述事务也是如此:
成员变量:对应事务的属性 成员方法:对应事务的行为
类的定义格式
1 public class ClassName { 2 //成员变量 3 //成员方法 4 }
- 定义类:就是定义类的成员,包括成员变量和成员方法.
- 成员变量:和以前定义变量几乎是一样的。只不过位置发生了改变。在类中,方法外。
- 成员方法:和以前定义方法几乎是一样的。只不过把static去掉,static的作用在面向对象后面课程中再详细 讲解。
类的定义格式举例:
1 public class Student { 2 //成员变量 3 String name;//姓名 4 int age;//年龄 5 //成员方法 6 //学习的方法 7 publicvoid study() { 8 System.out.println("好好学习,天天向上"); 9 } 10 //吃饭的方法 11 publicvoid eat() { 12 System.out.println("学习饿了要吃饭"); 13 } 14 }
对象的创建使用
对象的使用格式
创建对象:
类名 对象名 = new 类名();
使用对象访问类中的成员:
- 对象名.成员变量;
- 对象名.成员方法();
对象的使用格式举例:
public class Test01_Student { public static void main(String[] args) { //创建对象格式:类名 对象名 = new 类名(); Student s = new Student(); System.out.println("s:"+s); //cn.itcast.Student@100363 //直接输出成员变量值 System.out.println("姓名:"+s.name); //null System.out.println("年龄:"+s.age); //0 System.out.println("‐‐‐‐‐‐‐‐‐‐"); //给成员变量赋值 s.name = "赵丽颖"; s.age = 18; //再次输出成员变量的值 System.out.println("姓名:"+s.name); //赵丽颖 System.out.println("年龄:"+s.age); //18 System.out.println("‐‐‐‐‐‐‐‐‐‐"); //调用成员方法 s.study(); // "好好学习,天天向上" s.eat(); // "学习饿了要吃饭" }
}
成员变量的默认值