Java是一种面向对象编程语言,因此在使用Java进行编程时,面向对象的概念是非常重要的。以下是一些常见的面向对象编程概念在Java中的应用方式:
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void sayHello() {
System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
}
public static void main(String[] args) {
Person person1 = new Person("Alice", 25);
person1.sayHello();
}
}
public class Student extends Person {
private int studentId;
public Student(String name, int age, int studentId) {
super(name, age);
this.studentId = studentId;
}
public void study() {
System.out.println("Student " + name + " is studying.");
}
public static void main(String[] args) {
Student student1 = new Student("Bob", 20, 12345);
student1.sayHello();
student1.study();
}
}
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
以上是一些常见的面向对象编程概念在Java中的应用方式。通过合理地应用这些概念,可以写出结构清晰、易于维护和扩展的Java代码。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: java中serializable怎么使用