javaSE21/9/7

面向对象编程OOP

面向对象思想

  • 分类的思维模式,思考问题首先会解决问题需要哪些分类,再对这些类进行单独思考
  • 本质:以类的方式组织代码,以对象的组织封装数据
  • 三大特性:
    封装,继承,多态

方法

方法定义

  • 修饰符 返回值类型 方法名(){
    方法体
    return 返回值;
    }

方法调用

  • 静态方法
    有static关键字可以被main方法直接调用,是静态方法
public class Demo {//建一个Demo类
    public static void main(String[] args) {
        Student.eat();//可直接用类名.方法名()调用
    }
}
public class Student {//建一个Studebt类
    public static void eat(){//方法定义时加static为静态方法
        System.out.println("学生要去吃饭");
    }
}
  • 非静态方法
    不用借助static,调用方法时需要先对类进行实例化
public class Demo {//建一个Demo类
    public static void main(String[] args) {
        Student student = new Student();//先对类进行实例化,即建一个学生对象
        student.eat();//可用对象名.方法名()调用
    }
}
public class Student {//建一个Studebt类
    public void eat(){//方法定义时不加static为非静态方法
        System.out.println("学生要去吃饭");
    }
}
  • 值传递
    值传递是指在调用函数时将实际参数复制一份传递到函数中,这样在函数中如果对参数进行修改,将不会影响到实际参数。
public class Demo {
    public static void main(String[] args) {
        int a = 1;
        System.out.println(a);//输出1
        Demo.change(a);
        System.out.println(a);//输出还是1
    }
    public static void change(int a){
        a = 10;
    }
}
  • 引用传递
    本质还是值传递,引用传递是指在调用函数时将实际参数的地址传递到函数中,那么在函数中对参数所进行的修改,将影响到实际参数。

类与对象的关系

  • 类是一种抽象的具体类型,是对某类事务整体描述,但不能代表某一具体的事务
  • 对象是抽象概念的具体实例

创建与初始化对象

  • 使用new关键字创建对象
  • 一个类中只有属性和方法
public class App {//建一个类
    public static void main(String[] args) {
        Student xm = new Student();//对Student类进行实例化
        xm.name = "小明";//对xm这个对象的姓名属性进行赋值
        xm.age = 19;//对xm这个对象的年龄进行赋值
        System.out.println(xm.name);
        xm.study();//study方法没有static关键字,用对象名.方法名()调用方法
    }
}
public class Student {//建一个Student类
   String name;//定义一个姓名的属性
   int age;//定义一个年龄的属性
   public void study(){
      System.out.println(this.name+"学生在学习");
   }
}

构造器

  • alt+insert生成构造器,也称构造方法
  • 必须和类名相同
  • 必须没有返回类型,也不能写void
  • 作用:
    new本质在调用构造方法
    初始化对象
public class App {
    public static void main(String[] args) {
        //使用new实例化了一个对象
        Student student = new Student("xiaoming");//给了参数,就会调用有参构造,方法重载
        System.out.println(student.name);
    }
}
public class Student {
      String name;
      public Student(){//构造方法,默认生成,无参构造
            this.name = "xiaoming";
      }
      public Student(String name){//有参构造,一旦定义了有参构造,默认生成的无参就必须显示定义,即手动写下无参构造
            this.name = name;
      }
}
posted @ 2021-09-07 22:01  想吃坚果  阅读(42)  评论(0)    收藏  举报