Java是一种面向对象的语言,也可以说Java是OOP(Object Oriented Programming)即面对对象编程。
- 面向过程
步骤清晰简单,一步一步往下做,适合处理一些比较简单的问题。
- 面向对象
物以类聚,分类的思维模式,首先思考问题需要哪些分类,然后对分类进行单独思考。最后对分类的细节进行面向过程的思索,面向对象适合处理复杂的问题,并且需要多人协作。
- 什么是面向对象
面向对象编程的本质就是:以类的方式组织代码,以对象组织(封装)数据。
面向对象三大特征:
封装
继承
多态
下面介绍一下Java方法(包含主函数public static void main)调用的一些规则(在一个类中):
- static修饰的方法可以直接调用static修饰的方法
- static修饰的方法调用非static修饰的方法时需要用new
- 非static修饰的方法调用static修饰的方法时可以直接调用
- 非static修饰的方法调用非static修饰的方法可以直接调用
package com.xzc.oop;
public class Student {
//static调用static
public static void main(String[] args) {
a();
}
public static void a(){
b();
}
public static void b(){
}
}
package com.xzc.oop;
public class Student {
//static调用非static
public static void main(String[] args) {
Student student = new Student();
student.b();
}
public static void a(){
Student student = new Student();
student.b();
}
public void b(){
}
}
package com.xzc.oop;
public class Student {
//非static调用static
public static void main(String[] args) {
}
public void a(){
b();
}
public static void b(){
}
}
package com.xzc.oop;
public class Student {
//非static调用非static
public static void main(String[] args) {
}
public void a(){
b();
}
public void b(){
}
}
- Java的传递类型
Java中全部都是值传递,没有引用传递。
package com.xzc.oop;
public class Student {
//值传递实例
public static void main(String[] args) {
int a = 1;
change(a);
System.out.println(a);//1
}
public static void change(int a){
a = 10;
}
}
即使是引用传递其本质也是值传递
package com.xzc.oop;
public class ValueTransform {
public static void main(String[] args) {
Person person = new Person();
System.out.println(person.name);//null
change(person);
System.out.println(person.name);//谢诏驰
}
public static void change(Person person){
person.name = "谢诏驰";
}
}
class Person{
String name;
}
- 类与对象
类是抽象的,而对象是实例化的真实的,一个类可以生成多个对象每个对象开始时除了对项目不同其余的方法、类变量......都是相同的。
以下Student作为方法类,Application作为主类,验证类与对象间的关系
package com.xzc.oop;
//一个项目应该只存在一个main方法 该类就是一个应用类所以不加main方法
public class Student{//方法类
String name;
int age;
public void study(){
System.out.println(this.name + "在学习");
}
}
package com.xzc.oop;
import com.xzc.oop.Student;
public class Application {//主类
public static void main(String[] args) {
//类是抽象的,需要进行实例化(new)
//对象是一个具体的实例
//student为一个对象(同一个类可以产生多种不同的对象)
Student student = new Student();
Student xzc = new Student();
Student zyj = new Student();
xzc.name = "xzc";
student.study();
xzc.study();//xzc在学习
zyj.study();//null在学习
}
}
总结:以类的形式组织代码,以对象的形式封装数据。