面向对象三大特征:
接下来让我们一一讲解:
概念:
要求:
核心词汇:
private
使用private定义类内属性后,不能直接在外部使用属性,只能在类内使用属性
private定义:
public class Student {
//私有属性:
private String name;
private int age;
private String sex;
//提供对外的public方法:
public String showName(){
return this.name;
}
public void changeName(String name){
this.name = name;
}
}
通常用private定义类内属性,再创建public方法调用类属性:
public class application {
public static void main(String[] args) {
Student xiaohong = new Student();
xiaohong.changeName("小红");
System.out.println(xiaohong.showName());
}
}
封装的功能:
本质:
使用方法:
public class 子类 extends 父类{
.......
}
注意点:
例子:
//main函数
public class application {
public static void main(String[] args) {
Person person = new Person();
person.say();
Student student = new Student();
student.say();
}
}
//父函数
public class Person {
public int debt;
public int objects;
private int money;
public void say(){
System.out.println("my nameHead is Hou");
}
}
//子函数
public class Student extends Person{
}
结果:
my nameHead is Hou
my nameHead is Hou
从上面我们可以看到即使子函数中没有任何代码,但子函数仍旧可以继承父函数的代码来实现main函数的要求
继承方法快捷键:
ctrl+H
原版name,this.name,super.name的区别:
//main函数
public class application {
public static void main(String[] args) {
Student student = new Student();
student.showName("侯");
student.showManner();
}
}
//父函数
public class People {
//父类姓名
String name = "HOU";
//方法
public void plan(){
System.out.println("people调用");
}
}
//子函数
public class Student extends People{
//子类姓名
String name = "hou";
//调用姓名:
public void showName(String name){
//调用输入的name
System.out.println(name);
//调用student的name
System.out.println(this.name);
//调用people的name
System.out.println(super.name);
}
//调用方法:
public void showManner(){
this.plan();
super.plan();
}
//方法
public void plan(){
System.out.println("student调用");
}
}
结果:
侯
hou
HOU
student调用
people调用
注意:
构造方法:
重写均为方法的重写
重写的定义:
重写的条件:
为什么要重写方法:
方法重写static和非static的区别:
代码演示:
//main函数
public class application {
public static void main(String[] args) {
A a = new A();
B b =new A();
//属于重写,a重写了b的plan1
a.plan1();
b.plan1();
//static只和左边定义类型油管
a.plan2();
b.plan2();
}
}
//父函数
public class B {
//非static方法:
public void plan1(){
System.out.println("i am b plan1");
}
//static方法:
public static void plan2(){
System.out.println("i am b plan2");
}
}
//子函数
public class A extends B{
//非static方法:
public void plan1(){
System.out.println("i am a plan1");
}
//static方法:
public static void plan2(){
System.out.println("i am a plan2");
}
}
一个对象的实际模型是确定的,但可以指向的引用模型是不确定的:
多态存在的条件:
注意:
父类定义的变量 可以指向 子类模型
父类 name = new 子类();
对象所能执行的方法取决于左侧的类型:
作用:
语法:
父类 instanceof 子类
结果:
true
false
例如:
object->people->student
object->people->teacher
存在上述两条继承线,则:
student instanceof object -> true
student instanceof teacher -> false
这里对类型转换不做过多赘述:
好的,针对面向对象的三大特征就概述到这里