面向对象
***:以事物为中心的编程思想,把待解决的问题分解成各个对象模型,并且设计各个对象所具有的属性和功能。使用的时候需要创建的对象,然后让这些对象去共同解决问题。
package pp;
public class Student {
public int age;
public String name =“tom”;
public Student(){
System.out.println(“这是一个构造方法”)
}
public void dd(){
System.out.println(“这是一个方法”)
}
}
类
:是一组相关的属性和行为的集合。(Student)
对象:是该事物的具体体现。(tom)
package pp;
public class StudentDemo {
public static void main(String[] args) {
Student stu =new Student();
//先new一个Student类中的对象stu
//使用stu.age=13;调用属性并给其赋值
//使用stu.dd();调用方法
System.out.println(“学生年龄”+stu.age);
}
}
2.在一个类中先定义属性变量那么属性分几种?
成员变量:在类中方法外,(位置)堆内存,随着对象的消失而消失,有默认的初始化值。
局部变量:在方法内,(位置)栈内存,随着方法的调用完毕而消失,先定义后赋值才能使用
public class People{
int age;//成员变量初始值为0;
public void show(){
//int age1;局部变量没有默认值
int age1=20;
//int age =23;局部和成员名字一样采用就近原则
System.out.println(age);
方法调用的时候访问的是成员变量
}
}
3.匿名对象
匿名对象:就是没有名字的对象。
匿名对象的应用场景:
A:调用方法,仅仅只调用一次的时候。
注意:调用多次的时候,不适合。
那么,这种匿名调用有什么好处吗?
有,匿名对象调用完毕就是垃圾。可以被垃圾回收器回收。
B:匿名对象可以作为实际参数传递
一般形式:类名 对象名=new 类名();
匿名形式:New 类名();
class Student{
public void show(){
System.out.println(“1111”);
}
}
class Student1{
public void demo(Student a){
a.show();
}
}
class People{
public static void main(String[] args){
Student s=new Student();
s.show();//一般调用方法
new Student().show();//匿名对象调用方法
Student1 st=new Student1();
st.demo(new Student());//匿名对象作为实际参数传递
}
}