java类的定义和使用
类的定义
/*
定义一个类,用来模拟“学生”事物,其中有两个组成部分
属性(是什么):
姓名
年龄
行为(能做什么)
吃饭
睡觉
学习
对应到java的类中
成员变量就是属性
String name; //姓名
int age; //年龄
成员方法就是行为
public void eat(){}//吃饭
public void sleep(){}//睡觉
public void study(){}//学习
*/
public class Student {
//成员变量
String name; //姓名
int age; //年龄
//成员变量
public void eat(){
System.out.println("吃饭");
}
public void sleep(){
System.out.println("睡觉");
}
public void study(){
System.out.println("学习");
}
}
类的使用
/*
通常情况下,一个类并不能直接使用,需要根据类创建一个对象才能使用
1、导包:指出需要使用的类在什么位置 import 包名称.类名称
如果和当前类在同一个包则可以省略不写
2.创建格式:
类名称 对象名 = new 类名称();
Studnet stu = new Student();
3.使用:
使用成员变量: 对象名.成员变量名;
使用成员方法: 对象名.成员方法名(参数);
注意事项:如果成员变量没有进行赋值,会有一个默认值,规则和数组一样
*/
public class TestStudent {
public static void main(String[] args) {
//根据Student类创建一个stu对象
Student stu = new Student();
//使用其中的成员遍历
System.out.println(stu.name);
System.out.println(stu.age);
//改变对象中成员变量的内容
stu.name="zs";
System.out.println(stu.name);
//使用对象的成员方法
stu.eat();
}
}
类作为函数的参数传递
public class Phone {
String brand;
double price;
String color;
//成员方法
public void call(String who){
System.out.println("给"+who+"打电话");
}
public void sendMessage(){
System.out.println("群发短信");
}
}
public class DemoPhoneParam {
public static void main(String[] args) {
Phone one = new Phone();
one.brand = "苹果";
one.price = 8388.0;
one.color = "土豪金";
method(one); //传递进去的参数其实就是地址值
}
//讲对象作为函数的参数传递
public static void method(Phone param){
System.out.println(param.brand);
System.out.println(param.price);
System.out.println(param.color);
}
}
类作为函数的返回值类型
类作为函数的返回值类型,返回的是该类的一个对象,可以通过新建一个该类的对象来接受函数返回的对象值
//Phone类
public class Phone {
String brand;
double price;
String color;
//成员方法
public void call(String who){
System.out.println("给"+who+"打电话");
}
public void sendMessage(){
System.out.println("群发短信");
}
}
//
public class Demo05PhoneParam {
public static void main(String[] args) {
Phone two = getPhone(); //新的同类型对象two来接收函数返回的对象
System.out.println(two.brand);
System.out.println(two.price);
System.out.println(two.color);
}
//类作为函数的返回值类型
public static Phone getPhone(){
Phone one = new Phone();
one.brand = "苹果";
one.price = 8388.0;
one.color = "玫瑰金";
return one; //谁调用该函数,函数就把对象返回给谁
}
}