JavaSE基础(下)
day09-动漫美女拼图
一、继承概述
1、什么是继承
- 继承是面向对象三大特征之一(
封装
,继承
和多态
) - 可以使得
子类具有父类的属性和方法
,还
可以在子类中重新定义
,追加属性和方法
;
继承的格式
- 格式:public class 子类名 extends 父类名 { }
- 范例:
public class Zi extends Fu { }
- Fu:是父类,也被称为基类、超类
- Zi:是子类,也被称为派生类
继承的使用
JLabel、JButton、JTextField、JTextArea
这些我们之前用到过的,都涉及到了继承;
public void setBounds(int x, int y, int width, int height)
也涉及到了继承
继承的好处之一:提高了代码的复用性
;
2、继承的练习
需求:使用继承的方式,改写用户登录界面展示的案例
package com.chuangTi;
import javax.swing.*;
public class UserLoginFrame extends JFrame { //子类继承自JFrame父类;
public UserLoginFrame() { //无参构造方法;
//窗体初始化
initFrame(); //调用的第一个方法
//绘制窗体
paintView(); //调用的第二个方法
this.setVisible(true);
}
public void paintView() { //方法定义
//显示用户名文本
JLabel usernameLable = new JLabel("用户名");
usernameLable.setBounds(50, 50, 50, 20);
this.add(usernameLable);
//用户名输入框
JTextField usernameField = new JTextField();
usernameField.setBounds(150, 50, 180, 20);
this.add(usernameField);
//显示密码文本
JLabel passwordLable = new JLabel("密码");
passwordLable.setBounds(50, 100, 50, 20);
this.add(passwordLable);
//密码输入框
JPasswordField passwordField = new JPasswordField();
passwordField.setBounds(150, 100, 180, 20);
this.add(passwordField);
//登录按钮
JButton loginButton = new JButton("登录");
loginButton.setBounds(50, 200, 280, 20);
this.add(loginButton);
}
public void initFrame() { //方法定义
this.setTitle("用户登录");
this.setSize(400, 300);
this.setDefaultCloseOperation(3);
this.setLocationRelativeTo(null);
this.setAlwaysOnTop(true);
this.setLayout(null);
}
}
创建窗体对象直接测试使用
package com.chuangTi;
public class App {
public static void main(String[] args) {
UserLoginFrame userLoginFrame = new UserLoginFrame();
}
}
运行结果;