This chapter continues the previous chapter by continuing to introduce the concept of object-oriented programming, which has three main characteristics: inheritance, encapsulation, and polymorphism
But before that, we will introduce more of the relationship between objects and classes. By building a foundation, such as constructors, abstractions, and interfaces, we will be better prepared to face more complex object-oriented concepts later.
As mentioned earlier, when we create a new object, it inherits all the properties of the class, including the functions.
public class Newgpa{
public void report(char gpa){
System.out.println("Your gpa is : " + gpa);
}
public double grade(char gpa){
if(gpa == 'A') return 3.7;
else return 2.7;
}
public static void main(String[] args){
Newgpa gpa_check = new Newgpa();
gpa_check.report('A');
System.out.println("Your Final grade is : "+ gpa_check.grade('A'));
}
}
Back to the comparison of function prefix modifiers that we mentioned in Day 11: Functions, here is a program demo to show the difference:
public class Main{
public void modifier_is_public(){
System.out.println("Called by object");
}
static void modifier_is_static(){
System.out.println("Called without creating objects");
}
public static void main(String[] args){
/*'創造物件呼叫函數*/
Main public_obj = new Main();
public_obj.modifier_is_public(); //Called by object
/*直接呼叫函數*/
modifier_is_static(); //Called without creating objects
}
}