day5 2021 2 6 面向对象编程部分

面向对象

以类的方式组织代码,以对象的组织封装数据。

三大特征:封装 继承 多态

回顾方法的定义

package com.wang.oop;

//Demo1 类
public class Demo1 {

    //main 方法
    public static void main(String[] args) {

    }

    /*
    修饰符 返回值类型 方法名(变量){
         //方法体
        return 返回值;
        }
     */

    //return结束方法或者返回结果;
    
    public String sayHello(){
        return "hello,world";
    }

    public static  int max(int a,int b){
        return a>b?a:b; //三元运算符
    }

}

对象的调用

  • 分为静态方法(有static)

    对于静态方法的调用

    直接

    类名.方法名();

    package com.wang.oop;
    
    public class Demo2 {
        public static void main(String[] args) {
            student.say();
        }
    }
    
    
     ```
    

package com.wang.oop;

public class student {
public static void say(){
System.out.println(“学生说话了”);

}

}

   ```
  • 非静态方法(无static)
package com.wang.oop;

public class Demo2 {
    public static void main(String[] args) {
    //对象类型 对象名 = 对象值
        student student = new student();
        student.say();
    }
}

package com.wang.oop;

public class student {
    public void say(){
        System.out.println("学生说话了");

    }
}

值传递

package com.wang.oop;

//值传递
public class Demo4 {
    public static void main(String[] args) {
        int a = 1;
        System.out.println(a);
        Demo4.change(a);
        System.out.println(a);
    }
    
    //无返回值
    
    public static void change(int a){
        a = 10;
    }
}
======================================================
输出:
1
1

类与对象的关系

创建对象

package com.wang.oop;

//一个项目应该只存在一个main方法

public class Application {

    public static void main(String[] args) {

        //类:抽象的,实例化
        //类实例化之后回返回一个自己的对象
        //xiaoming xiaohong对象就是Student类的具体实例
        Student xiaoming = new Student();
        Student xiaohong = new Student();

        xiaoming.name="小明";
        xiaoming.age=3;

        System.out.println(xiaoming.name);
        System.out.println(xiaoming.age);

        xiaohong.name="小明";
        xiaohong.age=3;

        System.out.println(xiaohong.name);
        System.out.println(xiaohong.age);



    }


}

Student类

package com.wang.oop;

//学生类

public class Student {

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

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



}

构造器 也叫构造方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值