Java 基础技术知识点
Java 是一种广泛使用的面向对象的编程语言,它的基础技术知识点包括:
类和对象
类是一组属性和方法的集合,它是构成 Java 程序的基本单位,而对象是类的实例。
例如:
public class Person {
private String name;
private int age;
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return this.age;
}
}
// 实例化一个 Person 对象
Person person = new Person();
person.setName("John");
person.setAge(20);
String name = person.getName();
int age = person.getAge();
继承
继承是指一个类可以从另一个类继承属性和方法,从而减少代码的重复编写。
例如:
public class Student extends Person {
private String school;
public void setSchool(String school) {
this.school = school;
}
public String getSchool() {
return this.school;
}
}
// 实例化一个 Student 对象
Student student = new Student();
student.setName("John");
student.setAge(20);
student.setSchool("MIT");
String name = student.getName();
int age = student.getAge();
String school = student.getSchool();
接口
接口是一组方法的声明,它可以被实现,从而实现多态。
例如:
public interface Animal {
void eat();
void sleep();
void move();
}
public class Dog implements Animal {
public void eat() {
System.out.println("Dog is eating");
}
public void sleep() {
System.out.println("Dog is sleeping");
}
public void move() {
System.out.println("Dog is moving");
}
}
// 实例化一个 Dog 对象
Dog dog = new Dog();
dog.eat();
dog.sleep();
dog.move();
泛型
泛型是指可以在编译时期检查类型安全的一种机制,它可以帮助程序员编写出更加健壮的代码。
例如:
public class Box {
private T value;
public void setValue(T value) {
this.value = value;
}
public T getValue() {
return this.value;
}
}
// 实例化一个 Box 对象
Box box = new Box<>();
box.setValue("Hello World!");
String value = box.getValue();
System.out.println(value);
通过上面的介绍,我们可以了解到 Java 基础技术知识点包括:类和对象、继承、接口、泛型等。