面向对象查漏补缺1

文章详细介绍了Java中的类定义,包括成员变量的默认值、方法的定义、构造器的使用,以及this和super关键字的作用。此外,还讨论了封装性、继承、多态和对象转型等面向对象编程的关键概念。
摘要由CSDN通过智能技术生成
成员变量都有默认值(null,0,'\0')
方法必须定义在类中
可变参数的方法在调用时,可以传0到多个
可变参数必须放到最后
可变参数在方法中最多有一个

在这里插入图片描述
堆:存放对象实例,所有的对象实例包括对象中的属性,以及数组都要在堆上分配
通常所说的栈,是指虚拟机栈。虚拟机栈用于存储局部变量等
方法区,存储已被虚拟机加载的类信息,常量,静态变量,即时编译器(JIT)编译后的代码等数据

class MyClass extends MySuperClass implements YourInterface {
}
In general, class declarations can include these components, in order:
Modifiers such as public, private, and a number of others that you will encounter later.
(However, note that the private modifier can only be applied to Nested Classes.)
The class name, with the initial letter capitalized by convention.
The name of the class's parent (superclass), if any, preceded by the keyword extends.
A class can only extend (subclass) one parent.
A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements.
A class can implement more than one interface.
The class body, surrounded by braces, {}.

封装性

# 权限修饰符
private:类内部使用
缺省:类内部,所在包内
protected:类内部,所在包内,其他包的子类
public:都可以
# 修饰类,只能用缺省和public
# 缺省类只能在所在包内使用

构造器

# 和类相同的名称
# 不声明返回类型
# 不能被static,final,synchronized,abstract,native修饰,不能有return语句

this

// this可以调用成员变量,方法,构造器
this:当前对象
this();	// 调用无参构造
this(12,"efewd");	// 调用参数为(int,String)的构造
this(parameter);	// 必须放在首行
this.doSport();	// 先在本类中找,找不到去父类找(子类会继承)

package和import

package com.guet;// 所在包名
import com.fundmental.sdd;// 包名.类名

继承

# 得到
子类会得到父类所有的成员变量和方法
# 使用
不同包,子类可以使用父类的protected和public成员
同一包,子类可以使用父类的缺省和protected和public成员

方法重写

# @Override
# 子类对父类继承过来的方法进行覆盖,覆写
# [方法名]和[形参列表]必须一致
# 重写后的权限修饰符 >= 父类那个方法的权限修饰符
# 子类不能重写父类中private的方法
# 返回类型
# 原方法是void\基本数据类型,重写后保持一致
# 原方法是引用数据类型,重写后可以相同或者是其子类

super

# super可以调用属性,方法,构造器
# 子类重写父类方法后,在子类中,想调用父类那个被重写的方法
# 子类中定义了同名属性,想调用父类那个
# super调用构造器
子类的构造器首行默认会调用super(); # 父类空参构造器
# super(parameter);必须声明在构造器首行
# 创建子类对象的过程中,一定会调用父类中的构造器
# 创建完子类对象后,内存中只有一个对象,new后面构造器对应的类的对象

在这里插入图片描述

多态

// 声明父类类型,new的是子类对象
Person p = new Man();
// 多态性的应用:虚拟方法调用
// 调用方法时
// 首先,这个方法在父类中必须要有(否则编译不过)
// 在子类中没有时,调用的是父类中的
// 编译时认为调用的是Person类中的eat()
// 执行时调用的是Man类中的eat()
p.eat();
// 调用属性时,找的是Person类中的
System.out.println(p.id);

转型

// 向上转型(多态)
fatherClass obj = new sonClass();
// 向下转型
// 儿子在左,爸爸在右
sonClass obj = (sonClass) fatherClass;
// 都会输出
// instanceof:对象是否是某个类的实例
People s = new Student();
if(s instanceof People){
    System.out.println("People");
}
if(s instanceof Student){
    System.out.println("Student");
}
// 也都会输出
Student s = new Student();
if(s instanceof People){
    System.out.println("People");
}
if(s instanceof Student){
    System.out.println("Student");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值