iT邦幫忙

2022 iThome 鐵人賽

DAY 17
0
自我挑戰組

30天Java由淺入深系列 第 17

Day 17 : The Relationship of Object and Class

  • 分享至 

  • xImage
  •  

Intro

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

  1. Inheritance: one class inherits the properties, functions, variables, etc., of another class (unidirectional inheritance)
  • a subclass corresponds to a superclass; a superclass can be inherited by multiple subclasses
  1. Encapsulation: A class controls the objects or other parts that are accessed by the rest of the class.
  2. Polymorphism: Use functions to perform multiple conditional tasks.

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.


Object call Function

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'));
	}
}
  • Program analysis: This program imports the GPA grading system, prints out and returns the score. Create a new object called gpa_check, which inherits the two functions of the original class.

Static vs. Public

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
	}
}
  • Program analysis: A simple observation can reveal that when Modifier is public, an object must be created before it can be called; otherwise, it can be called directly. In the future, when setting up a function to be referenced, special attention must be paid!!!

上一篇
Day 16 : Object and Class
下一篇
Day 18 : Constructors
系列文
30天Java由淺入深30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言