JavaDay06
面向对象
属性+方法就是一个类
面向对象编程的本质:以类的方式组织代码,以对象的组织封装数据。
三大特性
封装
继承
多态
从认识角度考虑先有对象后有类。对象是具体的事物。类是抽象的
从代码运行角度考虑是先有类后有对象。类是对象的模板。
方法的回顾:
静态方法:
public class Demo02 {
public static void main(String[] args) {
//实列化这个类 new
//对象类型 对象名 = 对象值;
//new Student().say();
Student student = new Student();
student.say();
}
//和类一起加载的 //先存在
public static void a(){
b();
}
//类实列化 之后才存在
public static void b(){
}
}
非静态方法:
public class Student {
//非静态方法
public void say(){
System.out.println("学生说话了。");
}
}
public static void main(String[] args) {
//实列化这个类 new
//对象类型 对象名 = 对象值;
//new Student().say();
Student student = new Student();
student.say();
}
形参与实参:
public class Demo03 {
public static void main(String[] args) {
//实际参数与形式参数的类型要一一对应
//System.out.println(new Demo03().add(3,2));
// Demo03 s = new Demo03();
// System.out.println(s.add(3,4));
int add = Demo03.add(2, 5);
System.out.println(add);
}
public static int add(int a, int b){
return a+b;
}
}
值传递与引用传递
public class Demo04 {
public static void main(String[] args) {
int a = 1;
System.out.println(a);
Demo04.change(a);
System.out.println(a);
}
public static void change(int a){
a = 10;
}
}
public class Demo05 {
public static void main(String[] args) {
Person person = new Person();
System.out.println(person.name);//null
Demo05.change(person);
System.out.println(person.name);//请将
}
public static void change(Person person){
//person是一个对象;指向的--->Person person = new Person(); 这是一个具体的人,可以改变属性!
person.name = "请将";
}
}
//定义了一个Person类 有一个属性:name
class Person{
String name;
}

浙公网安备 33010602011771号