1.类和对象
面向对象:方法 <==> 函数
现实世界的组成:世界是由对象组成的
对象:(Object Oriented Programming) 属性 + 方法
类:类似图纸,按照类可以创建出对象
抽取出共性的行为和特征,保留所关注的部分【业务使用的】
由类创建出的对象
类:定义了对象应具有的特征和行为,类是对象的模板
对象:拥有多个特征个行为的实体,对象是类的实例
public class Dog {
//属性 <==> 成员变量
String breed;
int age;
String sex;
String col;
//方法
//这个东西能做的事情
public void eat0(){
System.out.println(breed + "eating...");
}
public void eat1(){
String breed = "老八";
System.out.println(breed + "eating...");
}
public void eat2(){
String breed = "老八";
System.out.println(this.breed + "eating...");
}
//这三个的区别
public void sleeo(){
System.out.println(breed + "sleep...");
}
}
import java.net.SocketOption;
import java.util.Arrays;
import java.util.Scanner;
//方法 <-> 函数
public class Main {//类
public static void main(String[] args){
//gg是个地址在栈空间
//new Dog()这个操作是在堆空间中开辟的
Dog gg = new Dog();
gg.age = 18;
gg.col = "蓝色";
gg.breed = "小猫";
gg.sex = "公";
gg.eat();
gg.sleeo();
}
}
2.方法的重载
某些情况下,对象的同一种行为可能存在多种实现过程
例:人对象的“吃”的行为,虽然都是吃但吃的过程存在不同
重载(Overload):一个类中定义相同名称的方法
要求:1.方法名字相同
2.参数不同
3.与访问修饰符,返回值类型无关
public class Person {
int food;
public void eat(String ss){
System.out.println(ss);
}
public void eat(String str){
System.out.println(str);
}
}//构不成重载,会报错
public class Person {
String food;
public void eat(String ss){
System.out.println(ss);
}
public int eat(int a){
return a * a;
}
}//重载
public class Main {//类
public static void main(String[] args){
Person peo = new Person();
peo.food = "SHIT";
int b = peo.eat(5);
peo.eat("SHIT");
System.out.println(peo.food);
System.out.println(b);
}
}
3.构造方法
类中的特殊方法,主要用于创建对象
特点:名称与类名完全相同
没有返回类型(void也不可以)
只能通过new调用,不能通过.去调用
Ps:如果没有在类中显式定义构造方法,则编译器默认提供无参构造方法
public Person(){//默认的构造方法
System.out.println("Person() Executed");
}
加了有参构造后,编译器就不会自动加无参构造了
需要自己手写无参构造
Person peo = new Person();
对象创建过程:
1.在堆中开辟空间
2.为各个属性赋默认值
3.执行构造方法中的代码
4.将对象的地址赋给变量new
栈里面的地址指向了堆里面的空间【类似C语言中的指针】
peo实际上存的是一个地址指向堆中的数据
构造方法的重载
public class Person {
String name,gender;
int age;
//构造方法
public Person(){
}
public Person(String name){
this.name = name;
}
public Person(String name,int age){
this.name = name;
this.age = age;
}
}
public class Main {//类
public static void main(String[] args){
Person peo = new Person("老八",18);
Person peo1 = new Person("laoba");//对应的会被赋上值
Person peo2 = new Person();//全为默认值
}
}
4.this关键字
1调用实例属性,实例方法【全局变量】
public class Person {
String name,gender;
int age;
public void pt(){//谁调用了谁就是当前对象
System.out.println(this.name);
}
}
2.调用本类中其他构造方法
public class Person {
String name,gender;
int age;
//构造方法
public Person(){}
public Person(String name,String gender){
this.name = name;
this.gender = gender;
}
public Person(String name,String gender,int age){
this(name,gender);
this.age = age;
}
}