Java架构技术栈

Java中的基本数据类型与引用数据类型

2021-01-22  本文已影响0人  若丨寒

一、基本数据类型

Java中的基本数据类型与引用数据类型

Java数据大多数存放在堆栈中。

堆与栈的优缺点

举个栗子,如下图:

Java中的基本数据类型与引用数据类型

二、引用数据类型

1. Class(类)

2. Interface(接口)

3. Array(数组)

1.代码示例-Class:

public class Demo {
    String Name;
    int Age;
    double Score;
    Demo(String Name,int Age,double Score){
        //定义带三个参数的构造函数,进行初始化
        this.Name=Name;
        this.Age=Age;
        this.Score=Score;
    };
    public static void main(String[] args) {
        Demo d1=new Demo("小吴",20,98);
        Demo d2=new Demo("小天",19,80);
    }
  }
Java中的基本数据类型与引用数据类型

2.代码示例-Interface

interface Animal {//定义Animal接口
      public void eat();
      public void speak();
}
public class Dog implements Animal {//Dog类实现Animal接口 
      public void eat() {
            System.out.println("我喜欢吃骨头!");
    }
      public void speak() {
            System.out.println("汪汪汪!");
    }
      public static void main(String[] args) {
            Dog d=new Dog();
            d.eat();
            d.speak();
    }
}
  1. 接口不能用于实例化对象。
  2. 接口没有构造方法。
  3. 接口中所有的方法必须是抽象方法。
  4. 接口不能包含成员变量,除了 static 和 final 变量。
  5. 接口需要被类实现。
  6. 接口支持多继承。

3.代码示例-Array

public class Array {
      public static void main(String[] args) {
            int[] myList = new int[] {5,2,0,1,3,1,4};
      for(int list: myList) {
            System.out.print(list);
      }
      }
}

拓展1:

public static Comparable findMax(Comparable[] arr) {
      int maxIndex=0;
      for(int i=1;i<arr.length;i++)
            if(arr[i].compareTo(arr[maxIndex])>0)
                  maxIndex=i;
      return arr[maxIndex];
 }

拓展2:自动装箱与拆箱

来源:https://www.tuicool.com/articles/URJ7za6

上一篇 下一篇

猜你喜欢

热点阅读