面向对象

面向对象

本质:以类的方式组织代码,以对象的形式封装数据

  1. 方法不可以修改没有返回值的值,对象可以修改(类似于指针)
public class Demo01 {
    public static void main(String[] args) {
        Person person = new Person();

        System.out.println(person.name);

        change(person);
        System.out.println(person.name);

    }
    public static void change(Person person){
        person.name = "张三";
    }
}

class Person{
    String name;
}
  1. 类与对象的创建
package com.oop.demo02;

//学生类:抽象模板
public class Student {

    //属性:字段
    String name;
    int age;

    //方法
    public void study(){
        System.out.println(this.name + "在学习");
    }
}
package com.oop.demo02;

//1个项目应该只存在一个main方法,总测试类Application
public class Application {
    public static void main(String[] args) {
        //类:抽象的,实例化
        //类实例化后会返回一个自己的对象
        //student对象就是一个Student类的具体实例!

        Student xiaoming = new Student();
        xiaoming.name = "小明";

        xiaoming.study();
    }
}
  1. 构造器(构造方法)
  • 和类的名字相同
  • 没有返回类型和void

代码:

package com.oop.demo02;

public class Person {
    String name;
    //无参构造
    public Person(){
        this.name = "xiaoming";
    }
    //有参构造
    public Person(String name){
        this.name = name;
    }
    //alt+insert快捷键:快速生成构造器
}
package com.oop.demo02;

//1个项目应该只存在一个main方法,总测试类Application
public class Application {
    public static void main(String[] args) {
        //new 实例化了一个对象
        Person person = new Person("li");
        System.out.println(person.name);

        System.out.println(new Person().name);
    }
}
  1. 封装:属性私有,get/set
package com.oop.demo03;

//类   private:私有
public class Student {
    //属性私有
    private String name;
    private int id;
    private char sex;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public char getSex() {
        return sex;
    }

    public void setSex(char sex) {
        this.sex = sex;
    }

    //提供get\set方法
    public String getName(){
        return this.name;
    }
    public void setName(String name){
        this.name = name;
    }

}
package com.oop;

import com.oop.demo03.Student;

public class Application {
    public static void main(String[] args) {
        Student s1 = new Student();
        s1.setName("li");
        System.out.println(s1.getName());
    }


}
  1. 继承:extends
    • object类:超类
    • super,this:非常重要

在这里插入图片描述

  1. 多态

  2. static关键字

  • 静态代码块
  • 静态导入包
package com.oop.demo04;

//静态导入包
import static java.lang.Math.random;
public class Demo01 {
    public static void main(String[] args) {
        System.out.println(random());
    }
}
  1. 抽象类
  2. 接口

抽象的思想,学得好当架构师。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值