类:类是一个模板,它描述一类对象的行为和状态。
对象:对象是类的一个实例
一个类可以包含以下类型变量:
- 局部变量:在方法、构造方法或者语句块中定义的变量被称为局部变量。变量声明和初始化都是在方法中,方法结束后,变量就会自动销毁。
- 成员变量:成员变量是定义在类中,方法体之外的变量。这种变量在创建对象的时候实例化。成员变量可以被类中方法、构造方法和特定类的语句块访问。
- 类变量:类变量也声明在类中,方法体之外,但必须声明为static类型。
java类和对象使用实例:
package class_learning; public class Employee{ String name; int age; String designation; double salary; // Employee 类的构造器 public Employee(String name){ this.name = name; } // 设置age的值 public void empAge(int empAge){ this.age = empAge; } /* 设置designation的值*/ public void empDesignation(String empDesig){ designation = empDesig; } /* 设置salary的值*/ public void empSalary(double empSalary){ salary = empSalary; } /* 打印信息 */ public void printEmployee(){ System.out.println("名字:"+ name ); System.out.println("年龄:" + age ); System.out.println("职位:" + designation ); System.out.println("薪水:" + salary); } }
package class_learning; public class EmployeeTest{ public static void main(String[] args){ /* 使用构造器创建两个对象 */ Employee empOne = new Employee("RUNOOB1"); Employee empTwo = new Employee("RUNOOB2"); // 调用这两个对象的成员方法 empOne.empAge(27); empOne.empDesignation("高级程序员"); empOne.empSalary(1000); empOne.printEmployee(); empTwo.empAge(21); empTwo.empDesignation("菜鸟程序员"); empTwo.empSalary(500); empTwo.printEmployee(); } }