+ 5

java method overloading

Write a method called checkAge that takes in an int representing the year someone was born, and another Int representing the current year. The method should return an Int that is the person's (rough) current age age. Then overload that method with one that accepts a single int as the year someone was born and gives the current year argument a default value of 2018. Here is what I got so far: class Main { public static void main(String[] args) { } public static int checkAge(int birthYear, int currentYear){ return currentYear - birthYear; } public static int checkAge(int age){ return age; } }

3rd Apr 2019, 10:38 PM
Albert Yakubov
Albert Yakubov - avatar
5 Answers
+ 8
class Main { public static int checkAge(int birthYear, int currentYear){ return currentYear - birthYear; } public static int checkAge(int birthYear){ return checkAge(birthYear, 2018); } public static void main(String[] args) { } }
3rd Apr 2019, 10:45 PM
Hatsy Rei
Hatsy Rei - avatar
+ 5
Ummm, guys just making a silly comment that the current year is 2019. That's all I gotta say. OK I'll leave now.
4th Apr 2019, 11:03 AM
Sonic
Sonic - avatar
+ 1
hell yeah, thank you!!!!!!!!!
3rd Apr 2019, 10:51 PM
Albert Yakubov
Albert Yakubov - avatar
+ 1
I like what Hatsy did, having the overloading method call the overloaded one. I think that's the best way to do it, but here's another way that's a little more intuitive. class Main { private static int currentYear; public static int checkAge(int birthYear, int currentYear){ return currentYear - birthYear; } public static int checkAge(int birthYear){ currentYear = 2018; return currentYear - birthYear; } public static void main(String[] args) { } }
7th Apr 2019, 9:46 PM
Mark Matchen
Mark Matchen - avatar
0
import java.util.Scanner; class Main { public static int checkAge(int birthYear, int currentYear) { int c= currentYear - birthYear; System.out.println{c}; return c; } public static int checkAge(int birthYear){ return checkAge(birthYear, 2018); } public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.println{"enter your birth year "}; int a=sc.nextInt{}; System.out.println{"enter the current year "}; int b=sc.nextInt{}; Main.checkAge{a,b}; Main.checkAge{a}; } } if you want learn more visit http://pythonandmltrainingcourses.com/6-months-training-in-noida/
6th Apr 2019, 6:32 AM
navdeep