Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

The Ultimate FREE Java Course Part 2

3,231 views

Published on

Have you ever seen a Java course that is 'visual' in nature? The kind of lessons where you can see what happens when you are creating an object, doing method overloading, and using run-time polymorphism. I bet you haven't. Welcome to the most 'visual' Java course you will ever take.

This course teaches you everything you need to get started with Java programming. It divides each topic into explanation and example.

The explanation section deals with how a particular concept works in Java and covers the following:

Data Types & Variables, Typecasting,
Operators & Conditional statements such as if, if else, switch
Loops such as for, for each, while, and do while
Methods, Types of methods, Call by Value vs. Call by Reference, Variable Scope, Method Overloading,
Arrays and ArrayLists,
Classes and objects, How classes and objects work, and How primitive types vs. reference types are stored
Swing classes to take input from the user and command line methods to take input from the user such as BufferedReader, Scanner, Console,
Static variables, static methods, this keyword, super keyword, method overriding,
What is inheritance
And a real world example of run-time polymorphism that actually demonstrates what happens with vs. without polymorphism.
The example section covers an example for every concept discussed above. The course will be updated constantly to keep in sync with the real world developments in Java. So, are you ready to become a Java PRO?

Published in: Education

The Ultimate FREE Java Course Part 2

  1. 1. The Free Java Course that doesn’t SUCK Part 2
  2. 2. Saw Part 1? Part 1 covered all the newbie stuff, search for it J
  3. 3. Agenda 1. What is a class & Object 2. Buffered Reader 3. Scanner 4. Array List 5. Call By Value vs. Reference 6. Constructors & Overloading 7. Static keyword
  4. 4. Agenda 8. Enumerations 9. Scope vs. Lifetime 10. This keyword 11. Inheritance 12. Method overriding 13. Super keyword 14. Polymorphism
  5. 5. Where do I watch these videos? coursetro.com
  6. 6. What is a class? Simple = Grouping the Java data types to make your own types Complex = Trying to mock items in the real world… coursetro.com
  7. 7. What is your job? Take something in the real world and try to represent it in code coursetro.com
  8. 8. 1 What does it have? (Noun) [Properties] 2 What does it do? What can you do with it? (Verb) [Methods] coursetro.com
  9. 9. What does it have? (Noun) [Properties] Model Size (Width, height, length, breadth…) Weight … coursetro.com
  10. 10. What does it do/you can do? [Methods] Call Sms Take pictures/videos Play games … coursetro.com
  11. 11. 1 What does it have? (Noun) [Properties] 2 What does it do? What can you do with it? (Verb) [Methods] coursetro.com
  12. 12. 1 What does it have? (Noun) [Properties] Author Number of pages Publication name Title … coursetro.com
  13. 13. 1 What does it do or you can do with it? (Verb) [Methods] Read Make Notes … coursetro.com
  14. 14. Ask this question every time… Take anything in the real world, it can be a real object or a virtual tank inside your favorite game. What does it have? What does it do or what can you do with it? coursetro.com
  15. 15. class Phone{ //What does it have? Properties String model; double weight; … //What does it do or you can do? Methods public void call(){…}; public void sendSms(){…} public void takePictures(){…} public void playGames(){…} } coursetro.com
  16. 16. class Book{ //What does it have? Properties String author; int pages; String publicationName; String title; //What does it do or you can do? Methods public void read(){…}; public void makeNotes(){…} } coursetro.com
  17. 17. First Name Last Name Age Occupation Class Mark Murphy 35 Software Engineer Object 1 Jon Skeet 40 Developer Object 2 Frank Underwood 60 Congressman Object 3 Raymond Tusk 65 Entrepreneur Object 4 Zoe Barnes 30 Journalist Object 5 coursetro.com
  18. 18. The Conclusion Class = You create a type Object = You use your created type coursetro.com
  19. 19. 1. java class vs object 2. Java class vs method 3. Java class vs type 4. Java instance variable 5. Java instance method 6. difference between classes and objects 7. identifying classes and objects in ooad Google It!
  20. 20. How to make a Class? class Book{ //What does it have? Properties String author; int pages; //What does it do or you can do? Methods public int getPages(){…}; public void setPages(int number){…} } coursetro.com
  21. 21. How to make an Object? Book one = new Book(); Book two = new Book(); Book mine = new Book(); Book yours = new Book(); coursetro.com
  22. 22. When you make an object… one null one Book one; one = new Book(); one.author = “Herbert Schildt”; one Herbert Schildt author one.pages = 1000; one Herbert Schildt author pages = 1000
  23. 23. When you make an object… two null two Book two; two = new Book(); two.author = “J K Rowling”; two J K Rowling author two.pages = 1500; two J K Rowling author pages = 1500
  24. 24. Adding a method (accessor/getter) class Book{ String author; int pages; public int getPages(){ return pages; } } two J K Rowling author pages = 1500 int getPages() coursetro.com
  25. 25. Using a method public static void main(String[] args){ Book two = new Book(); two.author = “JK Rowling”; two.pages = 1500; …println(two.getPages()); } two J K Rowling author pages = 1500 int getPages() main()
  26. 26. Adding a method (mutator/setter) class Book{ String author; int pages; public int getPages(){ return pages; } public void setPages(int number){ pages = number; } } two J K Rowling author pages = 1500 int getPages() void setPages(int) coursetro.com
  27. 27. Using a method public static void main(String[] args){ Book two = new Book(); two.author = “JK Rowling”; two.pages = 1500; two.setPages(2000); …println(two.getPages()) //2000 } two J K Rowling author pages = 2000 int getPages() void setPages(int) main() 2000
  28. 28. Solve this problem User will give you length of each side/no of sides 1 side = Take that as the side of a square or radius of a circle 2 sides =Length and breadth of rectangle 3 sides= sides of triangle. Any other number of sides = Invalid Input Find the smallest, largest and average area. coursetro.com
  29. 29. What do we know from the problem? There are 4 shapes : circle, rectangle, square and triangle… coursetro.com
  30. 30. Let’s start with Square What does a square have? Length of each side Diagonal length Angles Area Perimeter … coursetro.com
  31. 31. Let’s start with Square What can you do with a square/square do? Calculate Area Calculate perimeter … coursetro.com
  32. 32. 1. What is a getter and setter method? 2. what is accessor and mutator method in java 3. java data members definition 4. java instance method 5. java dot operator 6. where are java objects created 7. java new keyword Google It!
  33. 33. What is a Stream? 0110 1100 1010 1011 0011 0101 1110 1111 0000Data Source Your Program InputStream OutputStream coursetro.com
  34. 34. 0 1 0 0 1 0 1 1 0 InputStream InputStream: Reads only 0s 1s coursetro.com
  35. 35. 0 1 0 0 1 0 1 1 0 InputStream InputStreamReader Input Stream Reader H i T h e r e ! Take the binary 0s and 1s from Input Stream and give you characters, But only 1 character at a time
  36. 36. 0 1 0 0 Input Stream BufferedReader Input Stream Reader Wh a t Take the characters from InputStreamReader and read the entire line in a single shot… Buffered Reader What
  37. 37. Need BufferedReader object BufferedReader reader = new BufferedReader(…); coursetro.com
  38. 38. Need InputStreamReader InputStreamReader isr = new InputStreamReader(…); BufferedReader reader = new BufferedReader(isr); coursetro.com
  39. 39. Need InputStream InputStreamReader isr = new InputStreamReader(System.in); BufferedReader reader = new BufferedReader(isr); coursetro.com
  40. 40. How do I take input? …println(“Enter your name”); InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); String yourName = br.readLine(); coursetro.com
  41. 41. I a m 2 6 y r Scanner Scanner I Take characters, split everything on the basis of ‘spaces’ by default am 2 6 y r
  42. 42. How does it work? System.out.println(“Enter whatever you want…”); Enter whatever you want… I am 26.5 years old! Scanner scan = new Scanner(System.in); I a m 2 6 . 5 y e a r s o l d ! After user hits enter, scanner splits input on the basis of spaces I a m 2 6 . 5 y e a r s o l d ! Each part is called a token, scanner has 5 tokens Use the next() method of the Scanner class to get each token
  43. 43. Click to watch videos below Classes and Objects Explained I Classes and Objects Explained II Classes and Objects Example Take Input From User Explained Take Input From User Example
  44. 44. 1. what is a stream in java 2. Java InputStream 3. Java OutputStream 4. Java BufferedReader 5. Java Scanner 6. Java Console 7. java scanner ioexception 8. bufferedreader vs scanner vs console 9. Scanner next java 10. Scanner nextLine Google It!
  45. 45. Why Array List? No need to worry about the size…Also be very specific about what type of elements you can store coursetro.com
  46. 46. Auto boxing and unboxing Primitive Type Wrapper Class byte Byte short Short int Integer long Long float Float double Double char Character boolean Boolean Double wrapper = 31.25; //Putting number into a box = autoboxing double d = wrapper; //Removing number from box = unboxing Doublewrapper = = 31.25value coursetro.com
  47. 47. How to make one? ArrayList list = new ArrayList(); //stores anything and everything ArrayList<String> list = new ArrayList<>(); //stores only Strings ArrayList<Integer> list = new ArrayList<>(); //stores only Integers coursetro.com
  48. 48. Method Name What does it do? add Adds element to the end of the ArrayList clear Removes all elements from ArrayList contains Returns true if ArrayList contains the element you specified, else false get Returns the element at the index you specify indexOf Returns index of first occurrence of the element you specified in the ArrayList remove Either specify the element and remove it when it occurs first or specify the index and remove the element at the index size Number of elements stored trimToSize Trim ArrayList to current number of elements
  49. 49. Lights! Camera! Action! ArrayList<String> list = new ArrayList(); list.add(“red”); list.add(0, “yellow”); list.add(“green”); list.remove(1); list.remove(“green”); list.contains(“yellow”) list list red list yellow red list yellow red green list yellow green list yellow true coursetro.com
  50. 50. For each loop String[] list =new String[10]; … for(String item : list){ …println(item); } ArrayList<String> list = new ArrayList<>(); … for(String item : list){ ...println(item); } coursetro.com
  51. 51. Array List References ArrayList<String> friends = new ArrayList<>(); friends.add(“Anky”); friends.add(“Gary”); ArrayList<String> people = friends; people.add(“Murphy”); ArrayList<String> friends = people = Anky Gary Murphy 0 1 2 coursetro.com
  52. 52. Array vs. Array List Size of list never changes = use Array Want a long list of numbers = use Array Else use ArrayList coursetro.com
  53. 53. Operation Arrays Array Lists Get an element e = values[2]; e = values.get(2); Replace an element values[3] = 12; values.set(3, 12); Size values.length values.size(); Remove element No inbuilt mechanism values.remove(4); Initialize fast int[] values = {7, 8, 9}; Call add() 3 times Arrays vs. Array Lists coursetro.com
  54. 54. 1. java arraylist to array 2. java array to arraylist 3. java arraylist vs array performance 4. java arraylist vs array memory usage 5. java wrapper class Google It!
  55. 55. What is a primitive variable byte, short, int, long, float, double, char, boolean are primitive types coursetro.com
  56. 56. Primitive type Properties Not initialized by default. If reassigned, new value replaces old byte, short, int. long, float, double & char have default value 0 boolean has default value false Stored on stack coursetro.com
  57. 57. What is a reference type Anything that is not a primitive type… coursetro.com
  58. 58. Reference Type Properties Store addresses Addresses point to objects Hence, they refer to objects Initialized to a default value of null Can call methods through their object Stored on heap coursetro.com
  59. 59. Memory Model …main(){ int i = 20; String x = “20”; } i = 20 x = address “20” Stack Heap
  60. 60. Call By Value Don’t modify things like ever! coursetro.com
  61. 61. …modify(int number){ number = 100; } …main(String[] args){ int original = 25; …println(“Before ”+original) //25 modify(original); …println(“After ”+original); //25 } coursetro.com
  62. 62. original 25 original 25 original 25 original 25 number 25 number 100 int original = 25; …println(“Before ”+original) //25 modify(original); …println(“After ”+original); //25 …modify(int number){ number = 100; } coursetro.com
  63. 63. Call By Reference Think carefully about what you are doing… coursetro.com
  64. 64. …modify(Square object){ object.side = 100; } …main(String[] args){ Square sq = new Square(); sq.side = 25; …println(“Before ”+sq.side); //25 modify(sq); ...println(“After ”+sq.side); //100 } coursetro.com
  65. 65. sq …main(String[] args){ Square sq = new Square(); sq.side = 25; …println(“Before ”+sq.side); //25 modify(sq); ...println(“After ”+sq.side); //100 } …modify(Square object){ object.side = 100; } side = 25 sq side = 25 sq side = 100 sq side = 100 object object coursetro.com
  66. 66. Array List Explained Array List Example Call by value vs. reference Explained Call by value vs. reference Example Relevant Videos Click To Watch Videos Below
  67. 67. 1. java call by value vs call by reference 2. java reference variable 3. java object or primitive 4. Stackoverflow error vs outofmemoryerror Google It!
  68. 68. Solve this problem User will give you length of each side/no of sides 1 side = Take that as the side of a square or radius of a circle 2 sides =Length and breadth of rectangle 3 sides= sides of triangle. Any other number of sides = Invalid Input Find the smallest, largest and average area. coursetro.com
  69. 69. 1 What does it have? (Noun) [Properties] 2 What does it do? What can you do with it? (Verb) [Methods] length breadth coursetro.com
  70. 70. What does it have? (Noun) [Properties] Length Breadth … coursetro.com
  71. 71. What does it do/you can do? [Methods] Calculate Area Calculate Perimeter Calculate Diagonal Lengths … coursetro.com
  72. 72. How to make a Rectangle? class Rectangle{ //What does it have? Properties double length; double breadth; //What does it do or you can do? //Methods public double getArea(){…}; } coursetro.com
  73. 73. How do we initialize stuff? double bill = 40.35; bill 40.35 Rectangle r = new Rectangle(); r How to make length = 20, breadth = 10 in the 1st step directly? length 0 breadth 0 r length 20 breadth 0 r.length = 20; r.breadth = 10; r length 20 breadth 10
  74. 74. What are constructors? Rectangle r = new Rectangle(); That! coursetro.com
  75. 75. The Default Constructor main() Rectangle has 2 properties : length, breadth Rectangle r = new Rectangle (); length = 0.0 breadth = 0.0…println(r.length + “ ” + r.breadth) Square() coursetro.com
  76. 76. Your Default Constructor main() Rectangle r = new Rectangle (); Rectangle(){ length = 20; breadth = 10; } …println(r.length + “ ” + r.breadth) coursetro.com
  77. 77. Your Custom Constructor Rectangle r = new Rectangle (20, 10); Rectangle(double l, double b){ length = l; breadth = b; } 20, 10 Rectangle r2 = new Rectangle (50, 40); 50, 40 coursetro.com
  78. 78. I want both Rectangles! Rectangle r = new Rectangle(); Rectangle r2 = new Rectangle(20, 10); coursetro.com
  79. 79. Your Overloaded Constructor Rectangle r = new Rectangle (); Rectangle(double l, double b){ length = l; breadth = b; } Rectangle r2 = new Rectangle (50, 40); Rectangle(){ length = 20; breadth = 10; } coursetro.com
  80. 80. Rules Has same name as class Doesn't return anything EVER! There is always a default constructor Unless you make it parameterized Called before other methods Called automatically coursetro.com
  81. 81. 1. method vs constructor in java 2. java constructor overloading 3. java default constructor 4. java parameterized constructor Google It!
  82. 82. static variables blocks methods imports inner classes coursetro.com
  83. 83. class Rectangle{ double length; double breadth; Rectangle(){ …println(“I was called”); } public double calculateArea(){…}; } Rectangle r = new Rectangle(); //I was called Rectangle r2 = new Rectangle(); //I was called coursetro.com
  84. 84. How many rectangles? Keep track of the number of rectangles created… coursetro.com
  85. 85. class Rectangle{ double length; double breadth; int count = 0; Rectangle(){ count = count + 1; } public double calculateArea(){…}; } Rectangle r = new Rectangle(); //1 Rectangle r2 = new Rectangle(); //1 coursetro.com
  86. 86. rRectangle r = new Rectangle(); length 0 breadth 0 count 1 r2Rectangle r2 = new Rectangle(); length 0 breadth 0 count 1 The Normal Way coursetro.com
  87. 87. The Static Way rRectangle r = new Rectangle(); length 0 breadth 0 r2Rectangle r2 = new Rectangle(); r3Rectangle r3 = new Rectangle(); count 1 length 0 breadth 0 length 0 breadth 0 23
  88. 88. class Rectangle{ double length; double breadth; static int count = 0; Rectangle(){ count = count + 1; } public double calculateArea(){…}; } Rectangle r = new Rectangle(); //1 Rectangle r2 = new Rectangle(); //2 coursetro.com
  89. 89. class Rectangle{ double length; double breadth; static int count = 0; Rectangle(){ count = count + 1; } public double calculateArea(){…}; } …main(String[] args){ ...println(Rectangle.count); } coursetro.com
  90. 90. Static Variables Rules Part of a class not object ClassName.variableName to access 1 copy maintained across objects of that class Methods in class can access static variables Keep common information static Primitive variables initialized to defaults Reference static variables initialized to null coursetro.com
  91. 91. Static Blocks class Rectangle{ … static int count = 0; Rectangle(){ count = count + 1; } } class Rectangle{ … static int count; static{ count = 0; } Rectangle(){ count = count + 1; } } coursetro.com
  92. 92. Load class Initialize static variables Run static blocks Run construc tor Other stuff coursetro.com
  93. 93. Static Methods Methods common to everyone… coursetro.com
  94. 94. r length 0 breadth 0 r2 r3 length 0 breadth 0 length 0 breadth 0 count 3 int getCount() void setCount(int) …main(String[] args){ ... main() println(Rectangle.getCount()); Rectangle.setCount(0); }
  95. 95. What about main? Static so that JVM can call it using ClassName.main for your class without objects coursetro.com
  96. 96. Constructors And Overloading Explained Constructors And Overloading Example Static Keyword Explained Static Keyword Example Relevant Videos Click To Watch Videos Below
  97. 97. 1. main method static in java 2. java static vs non static 3. Java static vs final 4. java when to use static 5. java static block vs static variable 6. Static block executed before main method 7. static method vs instance method 8. static rules in java 9. when to use static variables in java Google It!
  98. 98. How did I make constants so far? public class Workday{ static final String MONDAY = “Monday”; static final String TUESDAY = “Tuesday”; static final String WEDNESDAY = “Wednesday”; static final String THURSDAY = “Thursday”; static final String FRIDAY = “Friday”; } coursetro.com
  99. 99. How did I use them? public class Schedule { //Can be Workday.MONDAY, Workday.TUESDAY… String workday; } coursetro.com
  100. 100. What is an enumeration? A set of related constants… coursetro.com
  101. 101. Example Direction NORTH, SOUTH, EAST, WEST Days SUNDAY, MONDAY… Game Status CONTINUE, WON, LOST Pizza Sizes SMALL, MEDIUM, LARGE, EXTRA LARGE Employee Level INTERN, DEVELOPER, MANAGER, CEO Colors RED, GREEN, BLUE… coursetro.com
  102. 102. How to make one enum PizzaSize { SMALL, MEDIUM, LARGE, EXTRA_LARGE }; enum Workday { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY }; coursetro.com
  103. 103. How to use one? class Schedule { Workday workday; public Workday getWorkday(){ return workday; } public void setWorkday(Workday day){ workday = day; } } coursetro.com
  104. 104. Using enumeration with an if condition if( schedule.getWorkday() == Workday.FRIDAY ) { ...println(“Let’s party guys!”); } coursetro.com
  105. 105. Using enumeration with switch switch( schedule.getWorkday() ) { case MONDAY: case TUESDAY: case WEDNESDAY: case THURSDAY: …println(“Boring man!”); break; case FRIDAY: ...println(“Let’s party guys!”); break; } coursetro.com
  106. 106. Printing all the enumeration values for ( Workday w : Workday.values() ) { …println(w.name()); } coursetro.com
  107. 107. Add object oriented stuff… public enum Workday { MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY final String representation; Workday (String rep) { representation = rep; } (“Monday”), (“Tuesday”), (“Wednesday”), (“Thursday”), (“Friday”); public String getRepresentation() { return representation; } } for ( Workday w : Workday.values() ) { …println(w.getRepresentation()); } coursetro.com
  108. 108. Direct Input? valueOf()… covered in the practical video of this topic. coursetro.com
  109. 109. 1. Why use enums instead of constants 2. java enumeration interface 3. java enumeration methods 4. enumeration vs iterator example in java 5. enumeration name value 6. enumeration ordinal java Google It!
  110. 110. Scope vs. Lifetime Scope : the region in the program where variable is accessible Lifetime : the duration that a variable exists coursetro.com
  111. 111. Local Variables class Test { public void calculate(){ int x = 10; for(int i = 1...){ int prod = i * i; } } } Scope of x = Black box, Scope of i and prod = Green Box, Lifetime = White Box
  112. 112. Parameter Variables class Test { public static void setA(String t){ … ...println(t); } } Scope = Lifetime = Black Box Can’t add a local variable and parameter variable with the same name inside a method coursetro.com
  113. 113. Static Variables class Test { static String a = “Test”; public void display(){ …println(a); //Test } public static void setA(String t){ a = t; } } Scope = black box, Lifetime = as long as the program runs coursetro.com
  114. 114. Static Variable Hiding class Test { static String a = “Test”; public void display(){ int a = 20; …println(a); //20 ...println(Test.a); //Test } public static void setA(String a){ …println(a); //Parameter’s value ...println(Test.a); //Test Test.a = a; } } coursetro.com
  115. 115. Disjoint Scopes class Test { public void square(double number){ double result = … } public void cube(double number){ double result = … } } coursetro.com
  116. 116. Instance Variables class Test { String b = ”Test”; public void display(){ …println(b); //Test } public void setB(String t){ b = t; } } Scope = black box, Lifetime = as long as the object exists coursetro.com
  117. 117. Instance Variable Hiding class Test { String b = ”Test”; public void setB(String b){ …println(b); //prints the parameter’s value } } coursetro.com
  118. 118. This Keyword class Test { String b = ”Test”; public void setB(String b){ this.b = b; } } …main(String[] args){ Test one = new Test(); one.setB(“Hi”); Test two = new Test(); two.setB(“Bye”); Test three = new Test(); three.setB(“Vow”); } b “Test”one b “Test”two b “Test”three this “Hi” “Bye” “Vow”
  119. 119. This & constructors Covered in the practical session J coursetro.com
  120. 120. Enumeration Explained Enumeration Example This Keyword and variable hiding explained This keyword and variable hiding example Relevant Videos Click To Watch Videos Below
  121. 121. 1. java this keyword best practice 2. java this static context 3. this vs super in java 4. this keyword constructor java 5. static method this java 6. java this keyword usage 7. java println this Google It!
  122. 122. Without Inheritance Person • First Name • Last Name • Age Employee • First Name • Last Name • Age • Occupation • Salary Manager • First Name • Last Name • Age • Occupation • Salary • Department Managing Director • First Name • Last Name • Age • Occupation • Salary • Department • Experience • Branch
  123. 123. Without Inheritance Vehicle •Wheels •Fuel capacity •Weight •Mileage Bike • Wheels • Fuel capacity • Weight • Mileage • Seater capacity • Gears Car • Wheels • Fuel Capacity • Weight • Mileage • Seater capacity • Gears • Type • Storage capacity Truck •Wheels •Fuel Capacity •Weight •Mileage •Seater Capacity •Gears •Type •Storage capacity •Load capacity
  124. 124. Why Inheritance? Stop repeating yourself, try to find common stuff and declare them only once… coursetro.com
  125. 125. With Inheritance Managing Director Experience Branch Manager Department Employee Occupation Salary Person First Name Last Name Age coursetro.com
  126. 126. With Inheritance Truck Load Capacity Car Bike Seater Capacity Gears Vehicle Wheels Fuel Capacity Weight Mileage Type Storage Capacity
  127. 127. Solve this problem User will give you length of each side/no of sides 1 side = Take that as the side of a square or radius of a circle 2 sides =Length and breadth of rectangle 3 sides= sides of triangle. Any other number of sides = Invalid Input Find the smallest, largest and average area. coursetro.com
  128. 128. The Shape Hierarchy Shape Circle Rectangle Square Triangle coursetro.com
  129. 129. Shape and Rectangle class Shape{ public void display(){ …println(“Displaying shape”); } } s r display() length 0.0 breadth 0.0 display() sq display() length 0.0 breadth 0.0 side 0.0 class Rectangle extends Shape { double length; double breadth; } class Square extends Rectangle{ double side; } coursetro.com
  130. 130. Inheritance Rules The parent = superclass/base class The child = subclass/derived class All fields and methods of superclass are inherited by subclass Subclass = specialized version of superclass Object = direct/indirect superclass for every class in Java No multiple inheritance coursetro.com
  131. 131. Object : The God class Every class without an extends clause automatically extends from Object. toString(), hashcode(), equals(), clone() … are some of the methods from Object class coursetro.com
  132. 132. 1. java inheritance types 2. java inheritance example 3. java superclass of all classes 4. java extends multiple classes 5. java extends keyword 6. java subclass vs superclass 7. java subclass override Google It!
  133. 133. What is Method Overriding? To change what the superclass method does, define it in your subclass and override it coursetro.com
  134. 134. Shape, Rectangle and Square class Shape{ public double getArea(){ return 0.0; } } s r sq getArea() length 0.0 breadth 0.0 getArea() length 0.0 breadth 0.0 getArea() side 0.0 returns 0.0 returns 0.0 returns 0.0 s = Shape, r = Rectangle, sq = Square objects class Rectangle extends Shape { double length; double breadth; } class Square extends Rectangle{ double side; }
  135. 135. Method Overriding class Shape{ public double getArea(){ return 0.0; } } s getArea() returns 0.0 s = Shape, r = Rectangle objects r length 0.0 breadth 0.0 getArea() returns l * b class Rectangle extends Shape { double length; double breadth; public double getArea(){ return length * breadth; } } coursetro.com
  136. 136. Method Overriding class Rectangle extends Shape { double length; double breadth; public double getArea(){ return length * breadth; } } r sq length 0.0 breadth 0.0 getArea() length 0.0 breadth 0.0 getArea() side 0.0 returns l * b returns side * side r = Rectangle, sq = Square objects class Square extends Rectangle{ double side; public double getArea(){ return side * side; } } coursetro.com
  137. 137. Difference Between Overloading 1. Within the Class 2. Different parameters 3. Works with static 4. Compile Time Overriding 1. With parent child classes 2. Same parameters 3. Doesn’t 4. Run Time coursetro.com
  138. 138. Constructor Chaining class Shape{ Shape(){ …println(“First”); }} s First r First Second sq First Second Third s = Shape, r = Rectangle, sq = Square objects class Rectangle extends Shape { Rectangle(){ …println(‘’Second”); }} class Square extends Rectangle{ Square(){ …println(‘Third”); }}
  139. 139. Super keyword Access superclass variable Call superclass method Call superclass constructor coursetro.com
  140. 140. How to call superclass variable? class Shape{ String name = “I am a shape”; } s r name name I am a shape I am a rectangle I am a shapedisplay() s = Shape, r = Rectangle objects class Rectangle extends Shape { String name = “I am a rectangle”; public void display(){ …println(name); ...println(super.name); } } coursetro.com
  141. 141. How to call superclass method? class Shape{ public void display(){ …println(“Which shape?”); } } s r display() display() Which shape Which shape Rectangle s = Shape, r = Rectangle objects class Rectangle extends Shape { @Override public void display(){ super.display(); …println(“Rectangle”); } } coursetro.com
  142. 142. How to call superclass constructors? class Shape{ Shape ( String name){ …println(name); } } s r Shape() … First Second Rectangle() s = Shape, r = Rectangle objects class Rectangle extends Shape { Rectangle(){ super(“First”); …println(“Second”); } } coursetro.com
  143. 143. Inheritance Explained Inheritance Example Super keyword and Method overriding Explained Super keyword and Method overriding Example Relevant Videos Click To Watch Videos Below
  144. 144. 1. java super keyword 2. java super vs this 3. java super vs override 4. java method overriding rules 5. java method overriding vs overloading 6. accidental overloading java 7. super keyword constructor in java 8. java constructor chaining 9. java static method override 10. java super keyword static Google It!
  145. 145. What is Polymorphism? Process objects with the same superclass as if they are all objects of the superclass coursetro.com
  146. 146. A closer look class Shape{ public double getArea(){ return 0.0; } } class Rectangle extends Shape{ double length; double breadth; … //Constructor public double getArea(){ return length * breadth; } } coursetro.com
  147. 147. Superclass variable = Subclass object class Square extends Rectangle{ double side; … //Constructor public double getArea(){ return side * side; } } …main(String[] args){ Square sq = new Square(20); Rectangle r = new Rectangle(20, 10); Shape s = sq; s.getArea(); //400 s = r; s.getArea(); //200 } coursetro.com
  148. 148. How does it work? Square sq = new Square(20); Rectangle r = new Rectangle(20, 10); Shape s = sq; s.getArea(); //400 s = r; s.getArea(); //200 sq length 0.0 breadth 0.0 getArea() side 20 r length 0.0 breadth 0.0 getArea() s coursetro.com
  149. 149. Polymorphism Properties 1. Access only the superclass properties/methods when referring to subclass object 2. Actual object decides which method is called at run time 3. Type of variable doesn't matter 4. Supports Class & Interface coursetro.com
  150. 150. Solve this problem User will give you length of each side/no of sides 1 side = Take that as the side of a square or radius of a circle 2 sides =Length and breadth of rectangle 3 sides= sides of triangle. Any other number of sides = Invalid Input Find the smallest, largest and average area. coursetro.com
  151. 151. Why should I use this? Covered in the practical session of this video coursetro.com
  152. 152. Click to watch videos below Polymorphism With Classes Explained Polymorphism With Classes Example
  153. 153. 1. java polymorphism example 2. java polymorphism types 3. superclass reference subclass object 4. compile time polymorphism vs runtime polymorphism in java 5. java polymorphism rules 6. java polymorphism real world example 7. java polymorphism real time example Google It!
  154. 154. Thank You From… coursetro.com

×