Skip to content

Phân biệt ý nghĩa và cách sử dụng overload và override trong Java

Khi làm việc với Java, một trong những khái niệm cực kỳ cơ bản nhưng rất quan trọng không thể không biết đó chính là overload và override. Tuy cơ bản, nhưng đây là những kiến thức được hỏi trong những lần phỏng vấn của các nhà tuyển dụng Java. Các câu hỏi như “Phân biệt overload và override?“, “lúc nào thì sử dụng overload và override?“. Bất ngờ khi tôi hỏi một số bạn lập trình Java có kinh nghiệm 1 năm với những câu hỏi trên, các bạn ấy trả lời chưa được chính xác cũng như chưa được nhưng các bạn ấy lại làm được. Nghĩa là làm được nhưng chưa hiểu bản chất. Trong bài này, tôi sẽ trả lời 2 câu hỏi ở đề bài để các bạn tiện theo dõi và tham khảo.

Để làm rõ 2 vấn đề trên, các bạn cần nắm hai khái niệm overload và override là gì trước rồi mới tiếp tục tìm hiểu tiếp.

overload và orderride trong java hình 2

Overload và Override là gì?

Overload (nạp chồng) là hai phương thức cùng tên nhưng số lượng tham số trong các phương thức khác nhau hoặc các loại dữ liệu của tham số khác nhau và nằm trong một class.

Override (ghì đè) là hai phương thức có cùng tên, cùng kiểu dữ liệu trả về, cùng phạm vi truy cập (Access Modifienằm ở hai class khác nhau.

Qua hai khái niệm trên thì các bạn cũng đã hiểu về sự khác biệt của Overload và Override. Để các bạn hiểu rõ hơn chúng ta sẽ xem ví dụ ở bên dưới:

Ví dụ về Overload

Ví dụ về Override 

Tạo class Animal

Ta có class Cat kế thừa từ class cha là Animal

Kế thừa là gì thì các bạn có thể tìm hiểu thêm nếu chưa biết, trong bài này tôi đang nói cụ thể cho các bạn hiểu về overload cũng như override trong Java. Cách sử dụng thì như hai ví dụ trên, tuy nhiên bây giờ tôi sẽ trả lời câu hỏi đó là…

Lúc nào thì sử dụng overload và override?

  • Sử dụng overload khi trong cùng một phương thức, chúng ta muốn làm thêm một công việc khác, ta sẽ dùng Overload.
  • Sử dụng override khi  trong cùng phương thức , chúng ta lại muốn làm khác đi ta sẽ dùng Override. (Khác đi ở đây là khác phần thân của method, chúng ta có thể sử dụng logic…)
  • overload và orderride trong java

Để các bạn thật dễ hiểu hơn nữa tôi sẽ lấy làm một ví dụ như sau:

Đầu tiên tôi nói về ví dụ hiểu về overload như thế nào: 

Giả sử bạn có 1 method dùng để connect đến n database server, theo lẽ thông thường thì bạn sẽ viết ra n method phục vụ việc kết nối ví dụ như :

  • connectDBSQL
  • connectDBOracle
  • connectDBMySSQL

Như các bạn thấy rằng, nếu có n db server thì chúng ta phải viết n method để connect. Làm như vậy sẽ có nhiều hạn chế, thay vì thế bạn sử dụng kỹ thuật overload để chỉ cần viết method có tên là connectDB với các tham số truyền vào tương ứng.

=> Điều này sẽ giúp phương thức của chúng ta tránh nhầm lẫn, có ý nghĩa và dễ nhớ.

Override được hiểu và sử dụng trong trường hợp nào?

Giả sử như tôi có một bài toán như sau: Tính lương của công ty A, lương bằng số ngày * 300000;

Như vậy tôi cần tạo class như sau:

Nhưng bay giờ, lương nhân viên của công ty B lại khác so với công ty A rằng lương được tính như sau: lương = soNgay* 200000 + 1000000.

Như vậy với bài toán này, thay vì chúng ta tạo mới một phương thức để tính và xử lý tính lương thì chúng ta sẽ kế thừa lại class LuongNVCongTyA và sau đó override lại phương thức luongNV, code sẽ như sau:

Qua đó các bạn thấy rằng, trong cùng một phương thức nhưng chúng ta muốn khác đi, với bài trên chúng ta đều có phương thức tính lương, nhưng mỗi công ty lại có cách tính riêng, nên chúng ta sẽ sử dụng override.

Với các trường hợp ví dụ trên, Overload ,Override không có nghĩa là làm code ngắn hơn, nó chỉ làm cho tên hàm của chúng ta có ý nghĩa và rõ ràng hơn.


Qua bài này, hy vọng các bạn nắm được các khái  niệm cũng như đã phân biệt được overload và override trong Java. Ý nghĩa và sử dụng khi nào tôi cũng đã trình bình như trên. Chúc các bạn thực hiện thành công!

Published inCâu hỏi phỏng vấnJAVA COREKINH NGHIỆM LẬP TRÌNHLẬP TRÌNH JAVA

31 Comments

  1. Hello my family member! I wish to say that this post
    is awesome, great written and include almost all significant infos.
    I’d like to see more posts like this .

  2. Dale Dale

    Hello my family member! I wish to say that this post
    is awesome, great written and include almost all significant infos.
    I’d like to see more posts like this .

  3. I just wanted to construct a quick comment to be able to say thanks to you for the fabulous advice you are placing on this site. My long internet search has at the end been honored with reasonable points to exchange with my relatives. I ‘d point out that many of us visitors actually are undeniably lucky to live in a great website with so many awesome people with very beneficial opinions. I feel very much blessed to have come across the web page and look forward to plenty of more fabulous minutes reading here. Thanks again for a lot of things.

  4. You made some first rate points there. I seemed on the internet for the difficulty and located most people will go together with together with your website.

  5. I want to show my appreciation to you just for rescuing me from this particular problem. Because of checking throughout the search engines and getting suggestions that were not productive, I thought my life was done. Existing without the presence of answers to the issues you’ve resolved as a result of your main short article is a critical case, as well as those that would have in a wrong way affected my entire career if I hadn’t come across your blog post. Your natural talent and kindness in handling almost everything was crucial. I’m not sure what I would’ve done if I had not discovered such a point like this. I am able to at this moment relish my future. Thanks a lot very much for this expert and results-oriented guide. I will not be reluctant to suggest the website to any person who ought to have counselling about this problem.

  6. I wanted to create you one little remark to thank you so much as before for those fantastic techniques you have documented on this site. It’s certainly shockingly generous with you to supply unhampered all that a lot of folks might have sold as an e book to generate some cash for their own end, most notably considering that you could possibly have done it in the event you wanted. Those good tips also acted like a fantastic way to be sure that the rest have the identical keenness just as my very own to learn significantly more in regard to this matter. I’m sure there are several more pleasurable periods in the future for individuals who discover your site.

  7. Thank you for your own labor on this blog. Kate enjoys setting aside time for investigation and it’s really obvious why. Almost all hear all regarding the dynamic way you convey insightful tips through this website and as well attract response from others on that concept plus my princess is always becoming educated a lot. Have fun with the remaining portion of the year. You have been doing a really great job.

  8. Youre so cool! I dont suppose Ive learn something like this before. So nice to seek out someone with some unique ideas on this subject. realy thanks for beginning this up. this web site is something that’s wanted on the internet, somebody with somewhat originality. useful job for bringing one thing new to the web!

  9. Thank you a lot for providing individuals with such a brilliant chance to check tips from here. It is often very brilliant and packed with a great time for me and my office colleagues to visit your site at a minimum thrice in 7 days to learn the newest issues you have got. And indeed, I’m always fascinated with the great concepts you give. Certain two tips in this posting are completely the most effective we have all had.

  10. This actually answered my downside, thank you!

  11. My spouse and i got quite ecstatic Louis could round up his reports through the entire ideas he got from your very own blog. It’s not at all simplistic to just be giving for free solutions that many men and women might have been trying to sell. And we all fully understand we’ve got the website owner to give thanks to for that. The illustrations you made, the easy site navigation, the friendships you will aid to instill – it’s got mostly fantastic, and it is assisting our son in addition to us reason why the article is brilliant, which is wonderfully important. Thank you for the whole thing!

  12. Thanks a lot for providing individuals with an extraordinarily remarkable opportunity to discover important secrets from here. It is often so useful and stuffed with amusement for me personally and my office co-workers to search your web site a minimum of thrice per week to study the newest stuff you will have. And definitely, I’m also always fulfilled with your mind-boggling hints you give. Selected 3 facts on this page are ultimately the finest I’ve ever had.

  13. Aw, this was a very nice post. In thought I would like to put in writing like this additionally ?taking time and actual effort to make a very good article?but what can I say?I procrastinate alot and on no account appear to get one thing done.

  14. Can I just say what a aid to seek out somebody who actually knows what theyre talking about on the internet. You positively know tips on how to bring a problem to gentle and make it important. More folks need to read this and understand this facet of the story. I cant consider youre not more popular since you undoubtedly have the gift.

  15. I simply needed to thank you very much yet again. I do not know the things that I would’ve accomplished without the type of creative concepts revealed by you over that subject. This was a real traumatic issue in my view, however , noticing the very professional fashion you solved it took me to weep with contentment. I will be thankful for your advice and even trust you recognize what an amazing job you are getting into teaching men and women using your web blog. Most probably you haven’t got to know all of us.

  16. Thank you a lot for providing individuals with remarkably spectacular chance to read articles and blog posts from this blog. It is often so brilliant and also stuffed with fun for me personally and my office mates to search your web site nearly 3 times in 7 days to read through the latest stuff you will have. And definitely, I am actually contented with your effective information served by you. Selected 2 points on this page are certainly the most impressive we have ever had.

  17. you could have a fantastic blog right here! would you like to make some invite posts on my blog?

  18. Thanks for every one of your labor on this web page. Ellie loves going through internet research and it is easy to understand why. All of us know all about the compelling form you give worthwhile suggestions via your website and as well as increase participation from some other people on this area of interest plus our favorite simple princess has been starting to learn a great deal. Take advantage of the rest of the year. You are always carrying out a glorious job.

  19. A lot of thanks for each of your labor on this site. Debby takes pleasure in going through investigation and it is easy to see why. We all hear all concerning the powerful manner you render worthwhile suggestions by means of the website and as well as recommend contribution from some other people on the article plus our daughter is truly starting to learn so much. Take pleasure in the remaining portion of the new year. You’re the one doing a superb job.

  20. I have to show my appreciation for your kindness giving support to folks who absolutely need help on this important situation. Your very own dedication to passing the solution all over had become extraordinarily useful and has surely permitted professionals like me to reach their ambitions. This important help denotes this much a person like me and somewhat more to my fellow workers. Regards; from each one of us.

  21. After research a number of of the blog posts in your web site now, and I really like your manner of blogging. I bookmarked it to my bookmark website list and will probably be checking again soon. Pls check out my web page as well and let me know what you think.

  22. The following time I read a weblog, I hope that it doesnt disappoint me as a lot as this one. I imply, I do know it was my option to read, but I truly thought youd have something fascinating to say. All I hear is a bunch of whining about one thing that you could possibly repair in case you werent too busy looking for attention.

  23. very good put up, i certainly love this website, carry on it

  24. I am only writing to make you be aware of of the amazing experience our girl encountered reading your site. She even learned too many details, not to mention what it is like to possess an ideal helping mindset to let others without difficulty have an understanding of some tortuous topics. You undoubtedly exceeded my expected results. Many thanks for churning out those warm and friendly, safe, revealing and also fun tips on this topic to Emily.

  25. I precisely had to thank you so much once again. I’m not certain what I would have achieved without the entire secrets shared by you over such a subject. It had been an absolute frustrating issue in my view, however , witnessing the professional avenue you dealt with it made me to leap over happiness. I’m just happier for this help and thus pray you are aware of a great job you are always doing training the others using your webblog. I am sure you’ve never got to know all of us.

  26. Thank you a lot for giving everyone remarkably wonderful chance to read critical reviews from here. It really is very beneficial plus stuffed with fun for me personally and my office co-workers to search your website minimum thrice in a week to find out the newest things you have. And definitely, I’m so at all times pleased with all the cool hints you give. Certain two ideas on this page are really the most efficient we have ever had.

  27. Nice post. I learn one thing more difficult on different blogs everyday. It’s going to all the time be stimulating to read content from different writers and apply a little bit one thing from their store. I抎 favor to use some with the content material on my blog whether you don抰 mind. Natually I抣l offer you a link in your web blog. Thanks for sharing.

  28. A powerful share, I just given this onto a colleague who was doing just a little analysis on this. And he actually purchased me breakfast as a result of I discovered it for him.. smile. So let me reword that: Thnx for the treat! But yeah Thnkx for spending the time to discuss this, I really feel strongly about it and love studying more on this topic. If attainable, as you grow to be expertise, would you thoughts updating your weblog with extra details? It is extremely useful for me. Large thumb up for this weblog publish!

Leave a Reply

Your email address will not be published. Required fields are marked *