以类的方式组织代码,以对象的封装数据
类是一种抽象的数据类型,它是对某一事物的完整描述
对象是抽象概念的具体实例
快捷键:alt+ins=生成构造器
//构造器(默认无参数)
public Student(String name,int age) {
this.name=name;
this.age=age;
}
将复杂的功能封装起来,对外开放一个接口,简单调用
super | this | |
---|---|---|
代表的对象 | 父类对象的应用 | 本身调用者这个对象 |
前提 | 需要继承 | 没有继承也可以用 |
ctrl+h可以查看继承关系
//父
protected void hello(){
System.out.println("hello 父类!");
return;
}
//子
@Override
public void hello() {
System.out.println("hello 子类");
}
不同的对象调用同样的方法但是做了不同的事情。
多态是方法的多态,属性没有多态
存在的条件:继承关系,方法需要重写,父类的引用指向子类的对象 ——也可以理解成表现形式
类型转换
子类转化成父类,向上转型
父类转成为子类,向下转型:强制转换
//类型转换 由高(父类)到底(子类)需要强转
Person person = new Student();
((Student) person).go();
//person.go(); error
Student student = (Student) new Person();
//student.go(); 没有go方法
private | default | protected | public | |
---|---|---|---|---|
同一类 | 1 | 1 | 1 | 1 |
同一包中的类 | 1 | 1 | 1 | |
子类(可以跨包) | 1 | 1 | ||
其他包的类 | 1 |
static 只加载一次
匿名构造类可以进行赋一些初值
public class Person {
static {//1
System.out.println("this is 静态代码块");
}
{//2
System.out.println("this is 匿名代码块");
}
public Person() {//3
System.out.println("this is 构造方法");
}
public static void main(String[] args) {
Person person = new Person();
System.out.println("===================");
Person person1 = new Person();
}
}
/*
输出
this is 静态代码块
this is 匿名代码块
this is 构造方法
===================
this is 匿名代码块
this is 构造方法
*/
public abstract class Action {
public abstract int add(int a,int b);
public abstract int del(int a,int b);
public abstract int mul(int a,int b);
}
注意:
接口中所有的定义方法都是抽象的public abstract
接口可以多继承,区别extends
public interface UserService {
void update();
}
public class UserServiceImpl implements UserService {
@Override
public void update() {
}
}
效果图
具体的操作:
原文:https://www.cnblogs.com/10134dz/p/13781375.html