第七章:面向对象
一、编程思想
二、对象
三、类的组成
class 类名 {// 1. 属性// 2. 方法}
数据类型 变量名 = 值 ;
![](https://img-blog.csdnimg.cn/direct/8809c42796c347919790a21a4fe4780e.png)
public static 返回值类型 函数名 ( 形参 ) {// 函数体}方法定义如下:public 返回值类型 方法名 ( 形参 ){// 方法体}
四、创建对象
类名 对象名 = new 类名 ();
五、方法的重载(overload)【开发+面试+考试重点】
个数不同:su() su(int a) su(int a,int b)顺序不同:su(int a,int b) su(int b,int a)
类型不同:su(int a) su(char a)
六、构造方法
public 类名 ( 形参 ){}
package demo;
public class TestTeachar1{
public static void main(String[] args){
Teacher t = new Teacher("刘","男","体育");
System.out.println(t.name+"-"+t.sex+"-"+t.course);
t.teacher();
}
}
/*
定义老师类:用于描述该类对象属性和方法
*/
class Teacher{
// 1.属性
String name;
char sex;
String course;
// 2.构造方法
public Teacher(){} // 无参
public Teacher(int n){} // 有参
public Teacher(String str){}
public void Teacher(String n,char s,String c){
System.out.println("Teacher(String,int,String)");
// 成员变量 = 局部变量
name = n;
sex = s;
course = c;
}
// 3.方法
public void teacher(){
System.out.println("讲课中....");
}
}
七、this的应用
package demo;
public class TestCup{
public static void main(String[] args){
Cup t = new Cup("富光",8.8,"透明");
System.out.println(t.brand+"-"+t.price+"-"+t.color);
t.work();
}
}class Cup{
String brand;
double price;
String color;
public Cup(){}
public Cup(String brand,double price,String color){
this.brand=brand;
this.price=price;
this.color=color;
}
public void work(){
System.out.println("我是一个杯子....");
}
}
八、引用
类名 引用名 = new 类名 ();
java.lang.NullPointerException( 空指针异常 )
(2) 引用应用在返回值上:对应类型的对象和引用都可以作为返回值进行返回