java面向对象思想
java面向对象思想
Last edited 2023-4-3
type
Post
status
Published
date
Feb 16, 2023
slug
summary
tags
学习
java
category
学习思考
icon
password
Property
Apr 3, 2023 01:08 PM

面向对象

面向对象是一种编程思想,它将复杂的现实世界建模成一系列的对象,把对象之间的关系表达出来,从而更加贴近现实世界的思维习惯。它是一种声明式编程,将用户的需求转换成实际的操作。面向对象思想可以把现实世界中的事物和关系映射成对象,并将这些对象之间的关系表达出来。当程序处理这些对象时,可以更加贴近人们的思维习惯,从而让程序更容易理解和维护。

特点

notion image

封装性

notion image

继承性

notion image
notion image

多态性

notion image
 

类与对象

notion image
notion image

类的封装

构造方法

静态方法

以下是错误示范:
notion image
notion image
notion image

this关键字

static关键字

 

继承extends

重写父类

super关键字

notion image
notion image

final关键字

notion image
notion image
notion image
notion image

抽象类

抽象类(可以包含抽象方法和普通方法)和接口(只能包含抽象方法)
notion image

接口

notion image
notion image
notion image
interface Animal { public void animalSound(); // 接口方法(不用写abstract关键字,接口方法默认为抽象的) public void sleep(); // 另一个接口方法(抽象的) } class Pig implements Animal { public void animalSound() { // 实现接口的方法 System.out.println("The pig says: wee wee"); } public void sleep() { // 实现接口的方法 System.out.println("Zzz"); } } class Main { public static void main(String[] args) { Pig myPig = new Pig(); // 创建 Pig 对象 myPig.animalSound(); myPig.sleep(); } }
在这个例子中,我们定义了一个Animal接口,然后在Pig类中实现了这个接口。Pig类需要实现接口中的所有方法,否则会报错。最后在Main类中调用了这个Pig对象的animalSound()sleep()方法。这种方式使得我们可以在不同的类中使用相同的接口,增加了代码的复用性和灵活性

多态

父类 对象1=new 子类(); 对象的类型转换 Object类:是一切类的父类

异常

try...catch和finally(程序填空) Throws关键字
 
  • 学习
  • java
  • Java学习基础JavaWeb