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代碼。