9.2 Definition and use of classes

How to define a class?
The process of defining a class is to combine the common attributes of a series of related things and the attributes of the process
things that are extracted . In the class, it is called the behavior of the member variable thing. In the class, it is called the member method.
How to create an object?
Class name object name = new class name();

How to use an object?
Object name. Variable name
Object name. Method name (...)

/*
  定义一个手机类
 */

public class phone {
    //成员变量:定义在类中,方法外的变量
    //品牌
    String brand;
    String model;
    String name;
    //成员方法:先不写static修饰符
    public void call(String name){
        System.out.println("给"+name+"打电话");
    }
    //发短信
    public void sendmile(){
        System.out.println("发短信");
    }
    //玩游戏
    public void playGame(){

        System.out.println("玩游戏");
    }
}

Class call

/*
手机的测试类
 */

public class TestPhone {
  //main方法是程序的主入口,所有 代码的执行都是从这里开始的。
    public static void main(String[] args) {
        //1.创建对象
        phone p=new phone();
        //2.调用成员变量,并打印。
        //给成员变量赋值
        p.brand="苹果";
        p.model="Xr";
        p.name="程序员";

        //打印成员变量的值
        System.out.println(p.brand);
        System.out.println(p.model);
        System.out.println(p.name);

        //3.调用成员方法
        System.out.println("------------");
        p.call("乔布斯");
        p.sendmile();
        p.playGame();

    }
}

Guess you like

Origin blog.51cto.com/15138685/2666504