SlideShare ist ein Scribd-Unternehmen logo
1 von 154
The Free Java Course
that doesn’t SUCK
Part 2
Saw Part 1?
Part 1 covered all the newbie stuff, search for it J
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
Agenda
8. Enumerations
9. Scope vs. Lifetime
10. This keyword
11. Inheritance
12. Method overriding
13. Super keyword
14. Polymorphism
Where do I watch these videos?
coursetro.com
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
What is your job?
Take something in the real world and try to represent it in code
coursetro.com
1 What does it have? (Noun)
[Properties]
2 What does it do? What can you do
with it? (Verb) [Methods]
coursetro.com
What does it have? (Noun)
[Properties]
Model
Size (Width, height, length, breadth…)
Weight
…
coursetro.com
What does it do/you can do?
[Methods]
Call
Sms
Take pictures/videos
Play games
…
coursetro.com
1 What does it have? (Noun)
[Properties]
2 What does it do? What can you do
with it? (Verb) [Methods]
coursetro.com
1 What does it have? (Noun)
[Properties]
Author
Number of pages
Publication name
Title
…
coursetro.com
1 What does it do or you can
do with it? (Verb) [Methods]
Read
Make Notes
…
coursetro.com
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
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
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
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
The Conclusion
Class = You create a type
Object = You use your created type
coursetro.com
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!
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
How to make an Object?
Book one = new Book();
Book two = new Book();
Book mine = new Book();
Book yours = new Book();
coursetro.com
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
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
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
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()
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
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
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
What do we know from the
problem?
There are 4 shapes : circle, rectangle, square and triangle…
coursetro.com
Let’s start with Square
What does a square have?
Length of each side
Diagonal length
Angles
Area
Perimeter
…
coursetro.com
Let’s start with Square
What can you do with a square/square do?
Calculate Area
Calculate perimeter
…
coursetro.com
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!
What is a Stream?
0110 1100 1010 1011 0011 0101 1110 1111 0000Data
Source
Your
Program
InputStream
OutputStream
coursetro.com
0 1 0 0 1 0 1 1 0
InputStream
InputStream: Reads only 0s 1s
coursetro.com
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
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
Need BufferedReader object
BufferedReader reader = new BufferedReader(…);
coursetro.com
Need InputStreamReader
InputStreamReader isr = new InputStreamReader(…);
BufferedReader reader = new BufferedReader(isr);
coursetro.com
Need InputStream
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(isr);
coursetro.com
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
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
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
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
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!
Why Array List?
No need to worry about the size…Also be very specific about
what type of elements you can store
coursetro.com
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
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
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
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
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
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
Array vs.
Array List
Size of list never changes = use Array
Want a long list of numbers = use
Array
Else use ArrayList
coursetro.com
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
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!
What is a primitive variable
byte, short, int, long, float, double, char, boolean are primitive
types
coursetro.com
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
What is a reference type
Anything that is not a primitive type…
coursetro.com
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
Memory Model
…main(){
int i = 20;
String x = “20”;
}
i = 20
x = address
“20”
Stack Heap
Call By Value
Don’t modify things like ever!
coursetro.com
…modify(int number){
number = 100;
}
…main(String[] args){
int original = 25;
…println(“Before ”+original) //25
modify(original);
…println(“After ”+original); //25
}
coursetro.com
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
Call By Reference
Think carefully about what you are doing…
coursetro.com
…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
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
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
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!
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
1 What does it have? (Noun)
[Properties]
2 What does it do? What can you do
with it? (Verb) [Methods]
length
breadth
coursetro.com
What does it have? (Noun)
[Properties]
Length
Breadth
…
coursetro.com
What does it do/you can do?
[Methods]
Calculate Area
Calculate Perimeter
Calculate Diagonal Lengths
…
coursetro.com
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
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
What are constructors?
Rectangle r = new Rectangle(); That!
coursetro.com
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
Your Default Constructor
main()
Rectangle r = new Rectangle ();
Rectangle(){
length = 20;
breadth = 10;
}
…println(r.length + “ ” + r.breadth)
coursetro.com
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
I want both Rectangles!
Rectangle r = new Rectangle();
Rectangle r2 = new Rectangle(20, 10);
coursetro.com
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
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
1. method vs constructor in java
2. java constructor overloading
3. java default constructor
4. java parameterized constructor
Google	It!
static
variables blocks methods imports
inner
classes
coursetro.com
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
How many rectangles?
Keep track of the number of rectangles created…
coursetro.com
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
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
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
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
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
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
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
Load
class
Initialize
static
variables
Run
static
blocks
Run
construc
tor
Other
stuff
coursetro.com
Static Methods
Methods common to everyone…
coursetro.com
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);
}
What about main?
Static so that JVM can call it using ClassName.main for your
class without objects
coursetro.com
Constructors
And Overloading
Explained
Constructors
And Overloading
Example
Static Keyword
Explained
Static Keyword
Example
Relevant
Videos
Click To Watch Videos Below
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!
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
How did I use them?
public class Schedule {
//Can be Workday.MONDAY, Workday.TUESDAY…
String workday;
}
coursetro.com
What is an enumeration?
A set of related constants…
coursetro.com
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
How to make one
enum PizzaSize {
SMALL,
MEDIUM,
LARGE,
EXTRA_LARGE
};
enum Workday {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY
};
coursetro.com
How to use one?
class Schedule {
Workday workday;
public Workday getWorkday(){
return workday;
}
public void setWorkday(Workday day){
workday = day;
}
}
coursetro.com
Using enumeration with an if condition
if( schedule.getWorkday() == Workday.FRIDAY ) {
...println(“Let’s party guys!”);
}
coursetro.com
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
Printing all the enumeration values
for ( Workday w : Workday.values() ) {
…println(w.name());
}
coursetro.com
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
Direct Input?
valueOf()… covered in the practical video of this topic.
coursetro.com
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!
Scope vs. Lifetime
Scope : the region in the program where variable is accessible
Lifetime : the duration that a variable exists
coursetro.com
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
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
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
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
Disjoint Scopes
class Test {
public void square(double number){
double result = …
}
public void cube(double number){
double result = …
}
}
coursetro.com
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
Instance Variable Hiding
class Test {
String b = ”Test”;
public void setB(String b){
…println(b); //prints the parameter’s value
}
}
coursetro.com
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”
This & constructors
Covered in the practical session J
coursetro.com
Enumeration
Explained
Enumeration
Example
This Keyword
and variable
hiding explained
This keyword
and variable
hiding example
Relevant
Videos
Click To Watch Videos Below
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!
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
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
Why Inheritance?
Stop repeating yourself, try to find common stuff and declare
them only once…
coursetro.com
With Inheritance
Managing Director
Experience Branch
Manager
Department
Employee
Occupation Salary
Person
First Name Last Name Age
coursetro.com
With Inheritance
Truck
Load Capacity
Car
Bike
Seater Capacity Gears
Vehicle
Wheels Fuel Capacity Weight Mileage
Type Storage Capacity
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
The Shape Hierarchy
Shape
Circle Rectangle
Square
Triangle
coursetro.com
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
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
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
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!
What is Method Overriding?
To change what the superclass method does, define it in your
subclass and override it
coursetro.com
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;
}
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
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
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
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”); }}
Super
keyword
Access superclass variable
Call superclass method
Call superclass constructor
coursetro.com
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
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
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
Inheritance
Explained
Inheritance
Example
Super keyword and
Method overriding
Explained
Super keyword and
Method overriding
Example
Relevant
Videos
Click To Watch Videos Below
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!
What is Polymorphism?
Process objects with the same superclass as if they are all
objects of the superclass
coursetro.com
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
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
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
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
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
Why should I use this?
Covered in the practical session of this video
coursetro.com
Click to watch videos below
Polymorphism
With Classes
Explained
Polymorphism
With Classes
Example
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!
Thank You From…
coursetro.com

Weitere ähnliche Inhalte

Was ist angesagt?

05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and ClassesIntro C# Book
 
The Ring programming language version 1.10 book - Part 100 of 212
The Ring programming language version 1.10 book - Part 100 of 212The Ring programming language version 1.10 book - Part 100 of 212
The Ring programming language version 1.10 book - Part 100 of 212Mahmoud Samir Fayed
 
Advanced Programming Lecture 5 Fall 2016
Advanced Programming Lecture 5 Fall 2016Advanced Programming Lecture 5 Fall 2016
Advanced Programming Lecture 5 Fall 2016BienvenidoVelezUPR
 
The Ring programming language version 1.7 book - Part 90 of 196
The Ring programming language version 1.7 book - Part 90 of 196The Ring programming language version 1.7 book - Part 90 of 196
The Ring programming language version 1.7 book - Part 90 of 196Mahmoud Samir Fayed
 
Chapter 2 - Getting Started with Java
Chapter 2 - Getting Started with JavaChapter 2 - Getting Started with Java
Chapter 2 - Getting Started with JavaEduardo Bergavera
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaSanjeev Tripathi
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstractionIntro C# Book
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstractionIntro C# Book
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...Intro C# Book
 
oops -concepts
oops -conceptsoops -concepts
oops -conceptssinhacp
 
38 object-concepts
38 object-concepts38 object-concepts
38 object-conceptsraahulwasule
 

Was ist angesagt? (20)

05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and Classes
 
Icom4015 lecture10-f16
Icom4015 lecture10-f16Icom4015 lecture10-f16
Icom4015 lecture10-f16
 
The Ring programming language version 1.10 book - Part 100 of 212
The Ring programming language version 1.10 book - Part 100 of 212The Ring programming language version 1.10 book - Part 100 of 212
The Ring programming language version 1.10 book - Part 100 of 212
 
Advanced Programming Lecture 5 Fall 2016
Advanced Programming Lecture 5 Fall 2016Advanced Programming Lecture 5 Fall 2016
Advanced Programming Lecture 5 Fall 2016
 
The Ring programming language version 1.7 book - Part 90 of 196
The Ring programming language version 1.7 book - Part 90 of 196The Ring programming language version 1.7 book - Part 90 of 196
The Ring programming language version 1.7 book - Part 90 of 196
 
Chapter 2 - Getting Started with Java
Chapter 2 - Getting Started with JavaChapter 2 - Getting Started with Java
Chapter 2 - Getting Started with Java
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
 
Icom4015 lecture4-f16
Icom4015 lecture4-f16Icom4015 lecture4-f16
Icom4015 lecture4-f16
 
Java basic
Java basicJava basic
Java basic
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
CIIC 4010 Chapter 1 f17
CIIC 4010 Chapter 1 f17CIIC 4010 Chapter 1 f17
CIIC 4010 Chapter 1 f17
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
 
Icom4015 lecture8-f16
Icom4015 lecture8-f16Icom4015 lecture8-f16
Icom4015 lecture8-f16
 
Icom4015 lecture3-f16
Icom4015 lecture3-f16Icom4015 lecture3-f16
Icom4015 lecture3-f16
 
oops -concepts
oops -conceptsoops -concepts
oops -concepts
 
38 object-concepts
38 object-concepts38 object-concepts
38 object-concepts
 
Icom4015 lecture14-f16
Icom4015 lecture14-f16Icom4015 lecture14-f16
Icom4015 lecture14-f16
 
Icom4015 lecture9-f16
Icom4015 lecture9-f16Icom4015 lecture9-f16
Icom4015 lecture9-f16
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 

Andere mochten auch

Andere mochten auch (20)

The power of creative collaboration
The power of creative collaborationThe power of creative collaboration
The power of creative collaboration
 
Yaazli International Hibernate Training
Yaazli International Hibernate TrainingYaazli International Hibernate Training
Yaazli International Hibernate Training
 
Yaazli International Web Project Workshop
Yaazli International Web Project WorkshopYaazli International Web Project Workshop
Yaazli International Web Project Workshop
 
For Loops and Variables in Java
For Loops and Variables in JavaFor Loops and Variables in Java
For Loops and Variables in Java
 
Yaazli International Spring Training
Yaazli International Spring Training Yaazli International Spring Training
Yaazli International Spring Training
 
Non ieee dot net projects list
Non  ieee dot net projects list Non  ieee dot net projects list
Non ieee dot net projects list
 
Savr
SavrSavr
Savr
 
Java quick reference v2
Java quick reference v2Java quick reference v2
Java quick reference v2
 
02basics
02basics02basics
02basics
 
Core java online training
Core java online trainingCore java online training
Core java online training
 
09events
09events09events
09events
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Toolbarexample
ToolbarexampleToolbarexample
Toolbarexample
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
 
Yaazli International AngularJS 5 Training
Yaazli International AngularJS 5 TrainingYaazli International AngularJS 5 Training
Yaazli International AngularJS 5 Training
 
DIWE - Using Extensions and Image Manipulation
DIWE - Using Extensions and Image ManipulationDIWE - Using Extensions and Image Manipulation
DIWE - Using Extensions and Image Manipulation
 
Java Basic Operators
Java Basic OperatorsJava Basic Operators
Java Basic Operators
 
Non ieee java projects list
Non  ieee java projects list Non  ieee java projects list
Non ieee java projects list
 
Singleton pattern
Singleton patternSingleton pattern
Singleton pattern
 
DIWE - Multimedia Technologies
DIWE - Multimedia TechnologiesDIWE - Multimedia Technologies
DIWE - Multimedia Technologies
 

Ähnlich wie The Ultimate FREE Java Course Part 2

Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0BG Java EE Course
 
Internet programming slide - java.ppt
Internet programming slide - java.pptInternet programming slide - java.ppt
Internet programming slide - java.pptMikeAdva
 
Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)jeffz
 
Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Cody Engel
 
DISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in JavaDISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in JavaRasan Samarasinghe
 
14. Defining Classes
14. Defining Classes14. Defining Classes
14. Defining ClassesIntro C# Book
 
The Ring programming language version 1.5.3 book - Part 6 of 184
The Ring programming language version 1.5.3 book - Part 6 of 184The Ring programming language version 1.5.3 book - Part 6 of 184
The Ring programming language version 1.5.3 book - Part 6 of 184Mahmoud Samir Fayed
 
Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................suchitrapoojari984
 
JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & AnswersRatnala Charan kumar
 
Extreme Swift
Extreme SwiftExtreme Swift
Extreme SwiftMovel
 
The Ring programming language version 1.2 book - Part 78 of 84
The Ring programming language version 1.2 book - Part 78 of 84The Ring programming language version 1.2 book - Part 78 of 84
The Ring programming language version 1.2 book - Part 78 of 84Mahmoud Samir Fayed
 
The Ring programming language version 1.8 book - Part 7 of 202
The Ring programming language version 1.8 book - Part 7 of 202The Ring programming language version 1.8 book - Part 7 of 202
The Ring programming language version 1.8 book - Part 7 of 202Mahmoud Samir Fayed
 

Ähnlich wie The Ultimate FREE Java Course Part 2 (20)

Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
 
DITEC - Programming with Java
DITEC - Programming with JavaDITEC - Programming with Java
DITEC - Programming with Java
 
Internet programming slide - java.ppt
Internet programming slide - java.pptInternet programming slide - java.ppt
Internet programming slide - java.ppt
 
Oop java
Oop javaOop java
Oop java
 
Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)
 
Core java - baabtra
Core java - baabtraCore java - baabtra
Core java - baabtra
 
CAP615-Unit1.pptx
CAP615-Unit1.pptxCAP615-Unit1.pptx
CAP615-Unit1.pptx
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 
Java practical
Java practicalJava practical
Java practical
 
Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)
 
DISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in JavaDISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in Java
 
14. Defining Classes
14. Defining Classes14. Defining Classes
14. Defining Classes
 
The Ring programming language version 1.5.3 book - Part 6 of 184
The Ring programming language version 1.5.3 book - Part 6 of 184The Ring programming language version 1.5.3 book - Part 6 of 184
The Ring programming language version 1.5.3 book - Part 6 of 184
 
Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................
 
JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & Answers
 
Extreme Swift
Extreme SwiftExtreme Swift
Extreme Swift
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Oop
OopOop
Oop
 
The Ring programming language version 1.2 book - Part 78 of 84
The Ring programming language version 1.2 book - Part 78 of 84The Ring programming language version 1.2 book - Part 78 of 84
The Ring programming language version 1.2 book - Part 78 of 84
 
The Ring programming language version 1.8 book - Part 7 of 202
The Ring programming language version 1.8 book - Part 7 of 202The Ring programming language version 1.8 book - Part 7 of 202
The Ring programming language version 1.8 book - Part 7 of 202
 

Kürzlich hochgeladen

Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 

Kürzlich hochgeladen (20)

Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 

The Ultimate FREE Java Course Part 2

  • 1. The Free Java Course that doesn’t SUCK Part 2
  • 2. Saw Part 1? Part 1 covered all the newbie stuff, search for it J
  • 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. Agenda 8. Enumerations 9. Scope vs. Lifetime 10. This keyword 11. Inheritance 12. Method overriding 13. Super keyword 14. Polymorphism
  • 5. Where do I watch these videos? coursetro.com
  • 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. What is your job? Take something in the real world and try to represent it in code coursetro.com
  • 8. 1 What does it have? (Noun) [Properties] 2 What does it do? What can you do with it? (Verb) [Methods] coursetro.com
  • 9. What does it have? (Noun) [Properties] Model Size (Width, height, length, breadth…) Weight … coursetro.com
  • 10. What does it do/you can do? [Methods] Call Sms Take pictures/videos Play games … coursetro.com
  • 11. 1 What does it have? (Noun) [Properties] 2 What does it do? What can you do with it? (Verb) [Methods] coursetro.com
  • 12. 1 What does it have? (Noun) [Properties] Author Number of pages Publication name Title … coursetro.com
  • 13. 1 What does it do or you can do with it? (Verb) [Methods] Read Make Notes … coursetro.com
  • 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. 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. 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. 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. The Conclusion Class = You create a type Object = You use your created type coursetro.com
  • 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. 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. How to make an Object? Book one = new Book(); Book two = new Book(); Book mine = new Book(); Book yours = new Book(); coursetro.com
  • 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. 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. 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. 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. 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. 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. 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. What do we know from the problem? There are 4 shapes : circle, rectangle, square and triangle… coursetro.com
  • 30. Let’s start with Square What does a square have? Length of each side Diagonal length Angles Area Perimeter … coursetro.com
  • 31. Let’s start with Square What can you do with a square/square do? Calculate Area Calculate perimeter … coursetro.com
  • 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. What is a Stream? 0110 1100 1010 1011 0011 0101 1110 1111 0000Data Source Your Program InputStream OutputStream coursetro.com
  • 34. 0 1 0 0 1 0 1 1 0 InputStream InputStream: Reads only 0s 1s coursetro.com
  • 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. 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. Need BufferedReader object BufferedReader reader = new BufferedReader(…); coursetro.com
  • 38. Need InputStreamReader InputStreamReader isr = new InputStreamReader(…); BufferedReader reader = new BufferedReader(isr); coursetro.com
  • 39. Need InputStream InputStreamReader isr = new InputStreamReader(System.in); BufferedReader reader = new BufferedReader(isr); coursetro.com
  • 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. What is a primitive variable byte, short, int, long, float, double, char, boolean are primitive types coursetro.com
  • 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. What is a reference type Anything that is not a primitive type… coursetro.com
  • 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. Memory Model …main(){ int i = 20; String x = “20”; } i = 20 x = address “20” Stack Heap
  • 60. Call By Value Don’t modify things like ever! coursetro.com
  • 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. 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. Call By Reference Think carefully about what you are doing… coursetro.com
  • 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. 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. 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. 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. 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. 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. What does it have? (Noun) [Properties] Length Breadth … coursetro.com
  • 71. What does it do/you can do? [Methods] Calculate Area Calculate Perimeter Calculate Diagonal Lengths … coursetro.com
  • 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. 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. What are constructors? Rectangle r = new Rectangle(); That! coursetro.com
  • 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. Your Default Constructor main() Rectangle r = new Rectangle (); Rectangle(){ length = 20; breadth = 10; } …println(r.length + “ ” + r.breadth) coursetro.com
  • 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. I want both Rectangles! Rectangle r = new Rectangle(); Rectangle r2 = new Rectangle(20, 10); coursetro.com
  • 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. 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. 1. method vs constructor in java 2. java constructor overloading 3. java default constructor 4. java parameterized constructor Google It!
  • 82. static variables blocks methods imports inner classes coursetro.com
  • 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. How many rectangles? Keep track of the number of rectangles created… coursetro.com
  • 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. 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. 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. 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. 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. 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. 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
  • 93. Static Methods Methods common to everyone… coursetro.com
  • 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. What about main? Static so that JVM can call it using ClassName.main for your class without objects coursetro.com
  • 96. Constructors And Overloading Explained Constructors And Overloading Example Static Keyword Explained Static Keyword Example Relevant Videos Click To Watch Videos Below
  • 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. 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. How did I use them? public class Schedule { //Can be Workday.MONDAY, Workday.TUESDAY… String workday; } coursetro.com
  • 100. What is an enumeration? A set of related constants… coursetro.com
  • 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. How to make one enum PizzaSize { SMALL, MEDIUM, LARGE, EXTRA_LARGE }; enum Workday { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY }; coursetro.com
  • 103. How to use one? class Schedule { Workday workday; public Workday getWorkday(){ return workday; } public void setWorkday(Workday day){ workday = day; } } coursetro.com
  • 104. Using enumeration with an if condition if( schedule.getWorkday() == Workday.FRIDAY ) { ...println(“Let’s party guys!”); } coursetro.com
  • 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. Printing all the enumeration values for ( Workday w : Workday.values() ) { …println(w.name()); } coursetro.com
  • 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. Direct Input? valueOf()… covered in the practical video of this topic. coursetro.com
  • 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. Scope vs. Lifetime Scope : the region in the program where variable is accessible Lifetime : the duration that a variable exists coursetro.com
  • 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. 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. 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. 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. Disjoint Scopes class Test { public void square(double number){ double result = … } public void cube(double number){ double result = … } } coursetro.com
  • 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. Instance Variable Hiding class Test { String b = ”Test”; public void setB(String b){ …println(b); //prints the parameter’s value } } coursetro.com
  • 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. This & constructors Covered in the practical session J coursetro.com
  • 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. 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. 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. 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. Why Inheritance? Stop repeating yourself, try to find common stuff and declare them only once… coursetro.com
  • 125. With Inheritance Managing Director Experience Branch Manager Department Employee Occupation Salary Person First Name Last Name Age coursetro.com
  • 126. With Inheritance Truck Load Capacity Car Bike Seater Capacity Gears Vehicle Wheels Fuel Capacity Weight Mileage Type Storage Capacity
  • 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. The Shape Hierarchy Shape Circle Rectangle Square Triangle coursetro.com
  • 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. 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. 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. 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. What is Method Overriding? To change what the superclass method does, define it in your subclass and override it coursetro.com
  • 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. 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. 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. 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. 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. Super keyword Access superclass variable Call superclass method Call superclass constructor coursetro.com
  • 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. 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. 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. Inheritance Explained Inheritance Example Super keyword and Method overriding Explained Super keyword and Method overriding Example Relevant Videos Click To Watch Videos Below
  • 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. What is Polymorphism? Process objects with the same superclass as if they are all objects of the superclass coursetro.com
  • 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. 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. 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. 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. 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. Why should I use this? Covered in the practical session of this video coursetro.com
  • 152. Click to watch videos below Polymorphism With Classes Explained Polymorphism With Classes Example
  • 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!