面向对象
以类的方式组织代码,以对象的组织封装数据。
三大特征:封装 继承 多态
回顾方法的定义
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+"在学习");
}
}