面向对象

it2024-10-10  45

面向对象

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

方法不可以修改没有返回值的值,对象可以修改(类似于指针) 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; } 类与对象的创建 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(); } } 构造器(构造方法) 和类的名字相同没有返回类型和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); } } 封装:属性私有,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()); } } 继承:extends object类:超类super,this:非常重要

多态

static关键字

静态代码块静态导入包 package com.oop.demo04; //静态导入包 import static java.lang.Math.random; public class Demo01 { public static void main(String[] args) { System.out.println(random()); } } 抽象类接口

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

最新回复(0)