Вы находитесь на странице: 1из 154

The Free Java Course

that doesnt 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
Object 1
Object 2

Mark

Murphy

35

Software
Engineer

Jon

Skeet

40

Developer

Frank

Underwood

60

Congressman Object 3

Raymond

Tusk

65

Entrepreneur

Object 4

Zoe

Barnes

30

Journalist

Object 5

coursetro.com

The Conclusion
Class =
Object =

You create a type


You use your created type

coursetro.com

Google It!
1.
2.
3.
4.
5.
6.
7.

java class vs object


Java class vs method
Java class vs type
Java instance variable
Java instance method
difference between classes and objects
identifying classes and objects in ooad

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


Book one;

one

one = new Book();

one

one.author = Herbert Schildt;

one

author

Herbert
Schildt

one

author

Herbert
Schildt

one.pages = 1000;

null

pages =

1000

When you make an object


Book two;

two

two = new Book();

two

two.author = J K Rowling;

two

author

JK
Rowling

two

author

JK
Rowling

two.pages = 1500;

null

pages =

1500

Adding a method (accessor/getter)


class Book{

String author;
int pages;

two

author
pages =

JK
Rowling
1500

public int getPages(){


return pages;

int getPages()

coursetro.com

Using a method
public static void main(String[] args){
Book two = new Book();
two.author = JK Rowling;

two

JK
Rowling

author
pages =

1500

two.pages = 1500;
println(two.getPages());

int getPages()

main()

Adding a method (mutator/setter)


class Book{
String author;

author

int pages;
public int getPages(){
return pages;
}

pages =

JK
Rowling
1500

two
int getPages()
void setPages(int)

public void setPages(int number){


pages = number;
}

coursetro.com

Using a method
public static void main(String[] args){
Book two = new Book();

author

two.author = JK Rowling;
two.pages = 1500;

pages =

JK
Rowling
2000

two
int getPages()

two.setPages(2000);

println(two.getPages()) //2000

void setPages(int)

}
2000

main()

User will give you length of each side/no of


sides

Solve this
problem

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

Lets start with Square


What does a square have?
Length of each side
Diagonal length
Angles
Area
Perimeter

coursetro.com

Lets start with Square


What can you do with a square/square do?
Calculate Area
Calculate perimeter

coursetro.com

Google It!
1.
2.
3.
4.
5.
6.
7.

What is a getter and setter method?


what is accessor and mutator method in java
java data members definition
java instance method
java dot operator
where are java objects created
java new keyword

What is a Stream?
InputStream

Data
Source

0110

1100

1010

1011

0011

0101

1110

1111

0000

Your
Program

OutputStream

coursetro.com

InputStream: Reads only 0s 1s


InputStream
0

coursetro.com

InputStreamReader
InputStream
0 1 00 1

01 10

Input
Stream
Reader

H i

The r e

Take the binary 0s and 1s from Input Stream and give you characters,
But only 1 character at a time

BufferedReader
Input
Stream
0 1 0 0

Input
Stream Wh a t
Reader

Buffered
Reader

What

Take the characters from InputStreamReader and read the entire line
in a single shot

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

Scanner

am

26

y r

Scanner

am 2 6

yr

Take characters, split everything on the basis of spaces by default

How does it work?


System.out.println(Enter whatever you want);
Scanner scan = new Scanner(System.in);

Enter whatever you want


I am 26.5 years old!

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

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

Google It!
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.

what is a stream in java


Java InputStream
Java OutputStream
Java BufferedReader
Java Scanner
Java Console
java scanner ioexception
bufferedreader vs scanner vs console
Scanner next java
Scanner nextLine

Why Array List?


No need to worry about the sizeAlso 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

wrapper =

Double
value

= 31.25

Double wrapper = 31.25;


//Putting number into a box = autoboxing
double d = wrapper;
//Removing number from box = unboxing

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

list.add(red);
list.add(0, yellow);
list.add(green);

list

red

list

yellow

red

list

yellow

red

list.remove(1);
list.remove(green);
list.contains(yellow)

list

yellow

green

list

yellow

green

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);

friends =
ArrayList<String>
people =

ArrayList<String> people = friends;


people.add(Murphy);

0
1
2

Anky
Gary
Murphy

coursetro.com

Size of list never changes = use Array

Array vs.
Array List

Want a long list of numbers = use


Array

Else use ArrayList

coursetro.com

Arrays vs. Array Lists


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

coursetro.com

Google It!
1.
2.
3.
4.
5.

java arraylist to array


java array to arraylist
java arraylist vs array performance
java arraylist vs array memory usage
java wrapper class

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
20
x = address

Stack

Heap

Call By Value
Dont 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

int original = 25;


println(Before +original) //25

original

25

modify(original);

original

25

number

25

original

25

number

100

original

25

modify(int number){
number = 100;

println(After +original); //25

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

main(String[] args){
Square sq = new Square();

sq

side = 25

sq

side = 25

object

sq

side =

100

object

sq

side =

100

sq.side = 25;
println(Before +sq.side); //25
modify(sq);

modify(Square object){
object.side = 100;
}
...println(After +sq.side); //100
}

coursetro.com

Click To Watch Videos Below


Array List
Example

Array List
Explained
Relevant
Videos
Call by value vs.
reference
Explained

Call by value vs.


reference
Example

Google It!
1.
2.
3.
4.

java call by value vs call by reference


java reference variable
java object or primitive
Stackoverflow error vs outofmemoryerror

User will give you length of each side/no of


sides

Solve this
problem

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

length

1 What does it have? (Noun)


breadth

[Properties]
2 What does it do? What can you do
with it? (Verb) [Methods]

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;

Rectangle r = new Rectangle();

r.length = 20;

r.breadth = 10;

bill

40.35

length
breadth

0
0

length
breadth

20
0

length
breadth

20
10

How to make length = 20, breadth = 10 in the 1st step directly?

What are constructors?


Rectangle r = new Rectangle(); That!

coursetro.com

The Default Constructor


main()

Square()

Rectangle r = new Rectangle ();

Rectangle has 2 properties :


length, breadth

println(r.length + + r.breadth)

length = 0.0
breadth = 0.0

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


20, 10

Rectangle(double l, double b){


length = l;
breadth = b;
}

Rectangle r = new Rectangle (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 r2 = new Rectangle (50, 40);

Rectangle(){
length = 20;
breadth = 10;
}
Rectangle(double l, double b){
length = l;
breadth = b;
}

coursetro.com

Has same name as class


Doesn't return anything EVER!

Rules

There is always a default constructor


Unless you make it parameterized
Called before other methods
Called automatically

coursetro.com

Google It!
1.
2.
3.
4.

method vs constructor in java


java constructor overloading
java default constructor
java parameterized constructor

static

variables

blocks

methods

imports

inner
classes

coursetro.com

class Rectangle{

double length;
double breadth;
Rectangle(){
println(I was called);
Rectangle r = new Rectangle();

//I was called

public double calculateArea(){};

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(){
Rectangle r = new Rectangle();

count = count + 1;

//1

Rectangle r2 = new Rectangle();

public double calculateArea(){};

//1

coursetro.com

The Normal Way


Rectangle r = new Rectangle();

Rectangle r2 = new Rectangle();

length
breadth
count

0
0
1

r2

length
breadth
count

0
0
1

coursetro.com

The Static Way


r

length
breadth

0
0

Rectangle r2 = new Rectangle();

r2

length
breadth

0
0

Rectangle r3 = new Rectangle();

r3

length
breadth

0
0

Rectangle r = new Rectangle();

count

3
12

class Rectangle{

double length;
double breadth;
static int count = 0;
Rectangle(){
Rectangle r = new Rectangle();

count = count + 1;

//1

Rectangle r2 = new Rectangle();

public double calculateArea(){};

//2

coursetro.com

main(String[] args){

class Rectangle{

double length;

...println(Rectangle.count);

double breadth;

static int count = 0;


Rectangle(){
count = count + 1;
}

public double calculateArea(){};


}

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{

class Rectangle{

static int count = 0;

static int count;

Rectangle(){

static{

count = count + 1;

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

main()
main(String[] args){

...

length
breadth

0
0
count

println(Rectangle.getCount());
Rectangle.setCount(0);

r2

length
breadth

0
0

int
getCount()

void
setCount(int)

r3

length
breadth

0
0

What about main?


Static so that JVM can call it using ClassName.main for your
class without objects

coursetro.com

Click To Watch Videos Below


Constructors
And Overloading
Explained

Constructors
And Overloading
Example

Relevant
Videos
Static Keyword
Explained

Static Keyword
Example

Google It!
1.
2.
3.
4.
5.
6.
7.
8.
9.

main method static in java


java static vs non static
Java static vs final
java when to use static
java static block vs static variable
Static block executed before main method
static method vs instance method
static rules in java
when to use static variables in java

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
Days
Game Status
Pizza Sizes
Employee Level
Colors

NORTH, SOUTH, EAST, WEST


SUNDAY, MONDAY
CONTINUE, WON, LOST
SMALL, MEDIUM, LARGE,
EXTRA LARGE
INTERN, DEVELOPER,
MANAGER, CEO
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 {

for ( Workday w : Workday.values() ) {

MONDAY (Monday),
TUESDAY (Tuesday),
WEDNESDAY (Wednesday),

println(w.getRepresentation());
}

THURSDAY (Thursday),
FRIDAY (Friday);
final String representation;
Workday (String rep) {
representation = rep;
}
public String getRepresentation() {
return representation;
}
}

coursetro.com

Direct Input?
valueOf() covered in the practical video of this topic.

coursetro.com

Google It!
1.
2.
3.
4.
5.
6.

Why use enums instead of constants


java enumeration interface
java enumeration methods
enumeration vs iterator example in java
enumeration name value
enumeration ordinal java

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

Cant 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);
...println(Test.a);
}
public static void setA(String a){
println(a);
...println(Test.a);
Test.a = a;
}
}

//20
//Test

//Parameters value
//Test

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 parameters 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);
}

one

Test
Hi

two

Test
Bye

three

Vow
Test

this

This & constructors


Covered in the practical session J

coursetro.com

Click To Watch Videos Below


Enumeration
Explained

Enumeration
Example

Relevant
Videos
This Keyword
and variable
hiding explained

This keyword
and variable
hiding example

Google It!
1.
2.
3.
4.
5.
6.
7.

java this keyword best practice


java this static context
this vs super in java
this keyword constructor java
static method this java
java this keyword usage
java println this

Without Inheritance

Person
First Name
Last Name
Age

Employee

First Name
Last Name
Age
Occupation
Salary

Managing
Director

Manager

First Name
Last Name
Age
Occupation
Salary
Department

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
Person

First Name

Last Name

Age

Employee

Occupation

Salary
Manager

Department
Managing Director
Experience
Branch

coursetro.com

With Inheritance
Vehicle

Wheels

Fuel Capacity

Mileage

Weight

Bike

Seater Capacity

Gears
Car

Type

Storage Capacity
Truck
Load Capacity

User will give you length of each side/no of


sides

Solve this
problem

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

Triangle

Square

coursetro.com

Shape and Rectangle


class Shape{
public void display(){

display()

display()
length 0.0
breadth 0.0

sq

display()
length 0.0
breadth 0.0
side
0.0

println(Displaying shape);
}
}
class Rectangle extends Shape {
double length;
double breadth;
}
class Square extends Rectangle{
double side;
}

coursetro.com

The parent = superclass/base class

Inheritance
Rules

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

Every class without an extends clause

Object : The
God class

automatically extends from Object.

toString(), hashcode(), equals(), clone()


are some of the methods from Object
class

coursetro.com

Google It!
1.
2.
3.
4.
5.
6.
7.

java inheritance types


java inheritance example
java superclass of all classes
java extends multiple classes
java extends keyword
java subclass vs superclass
java subclass override

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


s

class Shape{

getArea()

returns 0.0

getArea()

returns 0.0

public double getArea(){


return 0.0;

length

0.0

breadth

0.0

class Rectangle extends Shape {

getArea()

double length;

length

0.0

breadth

0.0

side

0.0

double breadth;
}
class Square extends Rectangle{
double side;
}

sq

returns 0.0

s = Shape, r = Rectangle, sq = Square objects

Method Overriding
s

class Shape{

getArea()

returns 0.0

getArea()

returns l * b

public double getArea(){


return 0.0;

}
}

length

0.0

breadth

0.0

class Rectangle extends Shape {


double length;
double breadth;
public double getArea(){
return length * breadth;
}

s = Shape, r = Rectangle objects

coursetro.com

Method Overriding
class Rectangle extends Shape {
double length;
public double getArea(){

returns l * b

getArea()

double breadth;

return length * breadth;

length

0.0

breadth

0.0

getArea()

class Square extends Rectangle{


double side;
public double getArea(){
return side * side;
}

sq

returns side * side

length

0.0

breadth

0.0

side

0.0

r = Rectangle, sq = Square objects

coursetro.com

Difference Between
Overloading

Overriding

1.
2.
3.
4.

1.
2.
3.
4.

Within the Class


Different parameters
Works with static
Compile Time

With parent child classes


Same parameters
Doesnt
Run Time

coursetro.com

Constructor Chaining
class Shape{

First

First
Second

sq

First
Second
Third

Shape(){
println(First); }}

class Rectangle extends Shape {


Rectangle(){
println(Second); }}

class Square extends Rectangle{


Square(){
println(Third); }}

s = Shape, r = Rectangle, sq = Square objects

Access superclass variable

Super
keyword

Call superclass method


Call superclass constructor

coursetro.com

How to call superclass variable?


class Shape{
String name = I am a shape;

name

I am a shape

name

I am a rectangle
I am a shape

}
class Rectangle extends Shape {
String name = I am a rectangle;

public void display(){


println(name);

display()

...println(super.name);
}
}

s = Shape, r = Rectangle objects

coursetro.com

How to call superclass method?


class Shape{
public void display(){

display()

Which shape

display()

Which shape
Rectangle

println(Which shape?);
}
}
class Rectangle extends Shape {
@Override
public void display(){
super.display();

println(Rectangle);
}
}

s = Shape, r = Rectangle objects

coursetro.com

How to call superclass constructors?


class Shape{
Shape ( String name){

println(name);

Shape()

Rectangle()

First
Second

}
}
class Rectangle extends Shape {
Rectangle(){
super(First);

println(Second);
}
}

s = Shape, r = Rectangle objects

coursetro.com

Click To Watch Videos Below


Inheritance
Example

Inheritance
Explained
Relevant
Videos
Super keyword and
Method overriding
Explained

Super keyword and


Method overriding
Example

Google It!
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.

java super keyword


java super vs this
java super vs override
java method overriding rules
java method overriding vs overloading
accidental overloading java
super keyword constructor in java
java constructor chaining
java static method override
java super keyword static

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{

class Rectangle extends Shape{

public double getArea(){

double length;
double breadth;

return 0.0;

//Constructor

public double getArea(){


return length * breadth;

}
}

coursetro.com

Superclass variable = Subclass object


class Square extends Rectangle{

main(String[] args){

double side;

Square sq = new Square(20);

//Constructor

Rectangle r = new Rectangle(20, 10);

public double getArea(){

Shape s = sq;

return side * side;

s.getArea();

//400

s = r;

s.getArea();

//200

coursetro.com

How does it work?


Square sq = new Square(20);
sq
Rectangle r = new Rectangle(20, 10);

getArea()
length 0.0
breadth 0.0
20
side

getArea()
length 0.0
breadth 0.0

Shape s = sq;
s.getArea();

//400

s = r;
s.getArea();

//200

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

User will give you length of each side/no of


sides

Solve this
problem

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

Google It!
1.
2.
3.
4.

java polymorphism example


java polymorphism types
superclass reference subclass object
compile time polymorphism vs runtime polymorphism in
java
5. java polymorphism rules
6. java polymorphism real world example
7. java polymorphism real time example

Thank You From

coursetro.

com

Вам также может понравиться