java基础(12)抽象类以及抽象方法abstract以及ArrayList对象使用

abstract

如同TS中abstract,只要被abstract修饰的类就不能被new也就是实例化,只能被派生类(子类)继承,抽象类中的抽象方法也必须在派生类中实现。

创建抽象类与子类继承抽象方法

abstract public class Test{
    
    
    abstract  int numAndNum(int a,int b);
    abstract  String strAndStr(String a,String b);
}
 class Zjq extends  Test{
    
    

    public  int numAndNum(int num1,int num2){
    
    
        return num1+num2;
    }

    public String strAndStr(String str1,String str2){
    
    
        return  str1+"和"+str2+"是好朋友。";
    }
 }

Tset作为Zjq的父类,Test被public关键字修饰说明我们可以在任何地方使用这个类,这个类为公开的,紧接着是abstract关键字说明我们这Test类变成了公开的抽象类,这个时候这个类已经不能被实例化了。再看它身上的两个方法,同样也都是被abstract修饰,所以这两个方法都必须在Zjq这个子类中具体实现出来。

在其他类中使用Zjq这个类


import java.util.Scanner;

public class TestPublic {
    
    
    public static void main(String[] args) {
    
    
        Zjq zjq = new Zjq();

        Scanner sc = new Scanner(System.in);
        
        System.out.println("请输入第一个数字:");
        int num1 = sc.nextInt();
        System.out.println("请输入第二个数字:");
        int num2 = sc.nextInt();
        int a = zjq.numAndNum(num1, num2);
        System.out.print("最终的结果为:");
        System.out.println(a);

        System.out.println("请输入第一个名称:");
        String str1 = sc.next();
        System.out.println("请输入第二个名称:");
        String str2 = sc.next();
        System.out.println(zjq.strAndStr(str1,str2));
    }
}

ArrayList

ArrayList就是动态数组,就是Array的复杂版本,它提供了动态的增加和减少元素,实现了ICollection和IList接口,灵活的设置数组的大小等好处。

import java.util.ArrayList;

public class TestPublic {
    
    
    public static void main(String[] args) {
    
    

        ArrayList<String> list = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
    
    
            list.add("我是第"+i+"个数");
        }
        String str =  list.get(6);//从0开始计算   我是第6个数
        System.out.println(str);

        String str3 = list.remove(7);
        System.out.println("删除的是:");
        System.out.println(str3);

        System.out.println(list.toString());
        System.out.println(list.size());
    }
}

在这里插入图片描述
上面只是使用到了几个常用的方法:
1.get
xx.get(index)返回值为当前下表的数组元素;
2.add
xx.add(yyy)向列表中添加元素,将指定的元素添加到此列表的尾部。
3.remove
xx.remove(index)返回值为当前下表的数组元素;删除index坐标下的元素
4.size
xx.size()获取当前list的长度。
other:

        System.out.println(list.isEmpty());//list是否为空;
        list.clear();//清除list所有元素
        System.out.println(list.isEmpty());//list是否为空

在这里插入图片描述
isEmpty判断当前list是否为空,空的话返回true;
clear将list所有元素清空;

猜你喜欢

转载自blog.csdn.net/qq_43291759/article/details/124079486