Sei sulla pagina 1di 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?

What is a class?

Simple = Grouping the Java data types to make your own types Complex = Trying to mock items in the real world…

What is your job?

Take something in the real world and try to represent it in code

1 What does it have? (Noun)

[Properties]

2 What does it do? What can you do

with it? (Verb) [Methods]

What does it have? (Noun)

[Properties]

Model

Size (Width, height, length, breadth…)

Weight

What does it do/you can do? [Methods]

Call

Sms

Take pictures/videos

Play games

1 What does it have? ( N o u n ) [Properties] 2 What does

1 What does it have? (Noun)

[Properties]

2 What does it do? What can you do

with it? (Verb) [Methods]

1 What does it have? ( N o u n ) [Properties] Author Number of

1 What does it have? (Noun)

[Properties]

Author

Number of pages

Publication name

Title

1 What does it do or you can do with it? (Verb) [Methods] Read Make

1 What does it do or you can

do with it? (Verb) [Methods]

Read

Make Notes

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?

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(){…}

class Book{ //What does it have? Properties String author; int pages; String publicationName ; String

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(){…}

First Name

Last Name

Age

Occupation

Class

     

Software

Mark

Murphy

35

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

The Conclusion

Class = Object =

You create a type You use your created type

Google It!

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

How to make a Class? class Book{ //What does it have? Properties String author; int

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){…}

}

How to make an Object? Book one = new Book(); Book two = new Book();

How to make an Object?

Book one = new Book();

Book two = new Book();

Book mine = new Book();

Book yours = new Book();

When you make an object

Book one;

one = new Book();

one.author = “Herbert Schildt”;

one.pages = 1000;

one

one one one one

one

one one one one

one

one one one one

one

null Herbert author Schildt Herbert author Schildt pages = 1000
null
Herbert
author
Schildt
Herbert
author
Schildt
pages =
1000
o ne.pages = 1000; one one one one null Herbert author Schildt Herbert author Schildt pages
o ne.pages = 1000; one one one one null Herbert author Schildt Herbert author Schildt pages

When you make an object

Book two;

two = new Book();

two.author = “J K Rowling”;

two.pages = 1500;

two

two two two two

two

two two two two

two

two two two two

two

null J K author Rowling J K author Rowling pages = 1500
null
J
K
author
Rowling
J
K
author
Rowling
pages =
1500
two.pages = 1500; two two two two null J K author Rowling J K author Rowling
two.pages = 1500; two two two two null J K author Rowling J K author Rowling

Adding a method (accessor/getter)

class Book{ String author; int pages;

public int getPages(){ return pages;

}

}

two

J K

Rowling

author

J K Rowling author pages = 1500 int getPages ()

pages =

1500

J K Rowling author pages = 1500 int getPages ()

int getPages()

int getPages(){ return pages; } } two J K Rowling author pages = 1500 int getPages

Using a method

public static void main(String[] args){ Book two = new Book(); two.author = “JK Rowling”; two.pages = 1500;

…println(two.getPages());

}

J K author two Rowling pages = 1500 int getPages() main()
J K
author
two
Rowling
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

public void setPages(int number){ pages = number; } } two J K Rowling author pages =

J K

Rowling

author

J K Rowling author pages = 1500 int getPages() void setPages (int)
pages = 1500 int getPages()
pages =
1500
int getPages()

void setPages(int)

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

}

J K author Rowling pages = 2000 two int getPages() void setPages(int) 2000 main()
J K
author
Rowling
pages =
2000
two
int getPages()
void setPages(int)
2000
main()

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.

What do we know from the problem?

There are 4 shapes : circle, rectangle, square and triangle…

Let’s start with Square

What does a square have?

Length of each side Diagonal length Angles Area Perimeter

Let’s start with Square

What can you do with a square/square do?

Calculate Area

Calculate perimeter

Google It!

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

What is a Stream?

Data Source
Data
Source
InputStream
InputStream
0110 1100 1010 1011 0011 0101 1110 1111 0000
0110
1100
1010
1011
0011
0101
1110
1111
0000
OutputStream
OutputStream

Your

Program

InputStream: Reads only 0s 1s

InputStream: Reads only 0s 1s InputStream 0 1 0 0 1 0 1 1 0 coursetro.
InputStream
InputStream

0

1

0

0

1

0 1 0 0 1 0 1 1 0

0

1

1

0

InputStream: Reads only 0s 1s InputStream 0 1 0 0 1 0 1 1 0 coursetro.

InputStreamReader

InputStreamReader InputStream Input 0 1 0 0 1 0 1 1 0 Stream Reader H i
InputStream Input 0 1 0 0 1 0 1 1 0 Stream Reader
InputStream
Input
0
1
0
0
1
0
1
1
0
Stream
Reader
Input 0 1 0 0 1 0 1 1 0 Stream Reader H i T h

H

i

H i T h e r e !

T

h

e

r

e

H i T h e r e !

!

Stream Reader H i T h e r e ! Take the binary 0s and 1s

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

BufferedReader

BufferedReader Input Stream Input 0 1 0 0 Stream Reader W h a t Buffered Reader
Input Stream Input 0 1 0 0 Stream Reader
Input
Stream
Input
0
1
0
0
Stream
Reader
Input Stream Input 0 1 0 0 Stream Reader W h a t Buffered Reader What
W h a t
W
h
a
t

Buffered

Reader

0 1 0 0 Stream Reader W h a t Buffered Reader What Take the characters

What

0 1 0 0 Stream Reader W h a t Buffered Reader What Take the characters

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

Need BufferedReader object

BufferedReader reader = new BufferedReader(…);

Need InputStreamReader

InputStreamReader isr = new InputStreamReader(…);

BufferedReader reader = new BufferedReader(isr);

Need InputStream

InputStreamReader isr = new InputStreamReader(System.in); BufferedReader reader = new BufferedReader(isr);

How do I take input?

println(“Enter your name”);

InputStreamReader isr = new InputStreamReader(System.in);

BufferedReader br = new BufferedReader(isr);

String yourName = br.readLine();

Scanner

Scanner I a m 2 6 y r Scanner I a m 2 6 y r
Scanner I a m 2 6 y r Scanner I a m 2 6 y r

I

a

m

2

6

y

r

Scanner

I a m 2 6 y r
I
a
m
2
6
y
r
a m 2 6 y r Scanner I a m 2 6 y r Take characters,

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

 

I

 

a

m

 

2

6

.

5

y

e

a

r

s

o

l

d

!

I
I
a m
a
m

2

6

.

5

y

e

a

r

s

o

l

d

!

Enter whatever you want… I am 26.5 years old!

After user hits enter, scanner splits input on the basis of spaces

Each part is called a token, scanner has 5 tokens

Use the next() method of the Scanner class to get each token

Google It!

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

Why Array List?

No need to worry about the size…Also be very specific about what type of elements you can store

Auto boxing and unboxing

Primitive

Wrapper

Type

Class

byte

Byte

short

Short

int

Integer

long

Long

float

Float

double

Double

char

Character

boolean

Boolean

wrapper =

Double

char Character boolean Boolean wrapper = Double value = 31.25 Double wrapper = 31.25; //Putting number

value

= 31.25

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

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

Method

What does it do?

Name

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    
   

list

list red

red

list

list yellow red  

yellow

red

 

list

list yellow red green

yellow

red

green

list

list yellow green

yellow

green

list

list yellow  

yellow

 

true

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

Array List References

ArrayList<String> friends = new ArrayList<>();

friends.add(“Anky”);

friends.add(“Gary”);

friends =

f riends.add (“Gary”); f riends = ArrayList<String> people = 0 Anky 1 Gary

ArrayList<String>

people =

0

Anky

1

Gary

2

Murphy

ArrayList<String> people = friends;

people.add(“Murphy”);

Array vs. Array List

Size of list never changes = use Array

Want a long list of numbers = use Array

Else use ArrayList

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

Google It!

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

What is a primitive variable

byte, short, int, long, float, double, char, boolean are primitive types

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

What is a reference type

Anything that is not a primitive type…

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

Memory Model

…main(){ int i = 20; String x = “20”;

}

i = 20 “20” x = address Stack Heap
i = 20
“20”
x = address
Stack
Heap

Call By Value

Don’t modify things like ever!

…modify(int number){

number = 100;

}

…main(String[] args){

int original = 25;

…println(“Before ”+original) //25

modify(original);

…println(“After ”+original);

//25

}

int original = 25;

…println(“Before ”+original) //25

modify(original);

…modify(int number){

number = 100;

}

…println(“After ”+original);

//25

original 25 original 25 number 25 original 25 number 100 original 25 coursetro.com
original
25
original
25
number
25
original
25
number
100
original
25
coursetro.com

Call By Reference

Think carefully about what you are doing

…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

…main(String[] args){ Square sq = new Square(); sq.side = 25; …println(“Before ”+sq.side); //25 sq side
…main(String[] args){
Square sq = new Square();
sq.side = 25;
…println(“Before ”+sq.side); //25
sq
side =
25
modify(sq);
sq
side =
25
object
…modify(Square object){
object.side = 100;
sq
side =
100
object
}
println(“After
”+sq.side);
//100
sq
side =
100
}
coursetro.com

Click To Watch Videos Below

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

Google It!

1. java call by value vs call by reference

2. java reference variable

3. java object or primitive

4. Stackoverflow error vs outofmemoryerror

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.

breadth length
breadth
length

1 What does it have? (Noun)

[Properties]

2 What does it do? What can you do

with it? (Verb) [Methods]

What does it have? ( N o u n ) [Properties] Length Breadth … coursetro.

What does it have? (Noun)

[Properties]

Length

Breadth

What does it do/you can do? [Methods] Calculate Area Calculate Perimeter Calculate Diagonal Lengths …

What does it do/you can do? [Methods]

Calculate Area

Calculate Perimeter

Calculate Diagonal Lengths

How to make a Rectangle? class Rectangle{ //What does it have? Properties double length; double

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(){…};

How do we initialize stuff?

double bill = 40.35;

Rectangle r = new Rectangle();

r.length = 20;

r.breadth = 10;

bill

40.35

r
r
 

length

0

breadth 0

breadth

0

r
r

length

20

breadth 0

breadth

0

r
r

length

20

breadth 10

breadth

10

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

What are constructors?

Rectangle r = new Rectangle(); That!

The Default Constructor

The Default Constructor main() Rectangle r = new Rectangle (); …println(r.length + “ ” + r.breadth)

main()

Rectangle r = new Rectangle ();

Default Constructor main() Rectangle r = new Rectangle (); …println(r.length + “ ” + r.breadth) Square()

…println(r.length + “ ” + r.breadth)

Rectangle (); …println(r.length + “ ” + r.breadth) Square() Rectangle has 2 properties : length, breadth

Square()

Rectangle has 2 properties :

length, breadth

+ “ ” + r.breadth) Square() Rectangle has 2 properties : length, breadth length = 0.0

length = 0.0 breadth = 0.0

Your Default Constructor

Your Default Constructor main() Rectangle r = new Rectangle (); …println(r.length + “ ” + r.breadth)

main()

Rectangle r = new Rectangle ();

Default Constructor main() Rectangle r = new Rectangle (); …println(r.length + “ ” + r.breadth) Rectangle(){

…println(r.length + “ ” + r.breadth)

= new Rectangle (); …println(r.length + “ ” + r.breadth) Rectangle(){ length = 20; breadth =

Rectangle(){ length = 20; breadth = 10;

}

Your Custom Constructor

Your Custom C onstructor 20, 10 Rectangle(double l, double b){ length = l; breadth = b;
Your Custom C onstructor 20, 10 Rectangle(double l, double b){ length = l; breadth = b;
20, 10
20, 10

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

}

Rectangle r = new Rectangle (20, 10);

50, 40
50, 40

Rectangle r2 = new Rectangle (50, 40);

I want both Rectangles!

Rectangle r = new Rectangle();

Rectangle r2 = new Rectangle(20, 10);

Your Overloaded Constructor

Your Overloaded Constructor Rectangle r = new Rectangle (); Rectangle r2 = new Rectangle (50, 40);

Rectangle r = new Rectangle ();

Rectangle r2 = new Rectangle (50, 40);

Rectangle (); Rectangle r2 = new Rectangle (50, 40); Rectangle(){ length = 20; breadth = 10;
Rectangle (); Rectangle r2 = new Rectangle (50, 40); Rectangle(){ length = 20; breadth = 10;
Rectangle (); Rectangle r2 = new Rectangle (50, 40); Rectangle(){ length = 20; breadth = 10;

Rectangle(){ length = 20; breadth = 10;

}

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

}

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

Google It!

1. method vs constructor in java

2. java constructor overloading

3. java default constructor

4. java parameterized constructor

static
static
static blocks methods imports variables inner classes coursetro. com
static blocks methods imports variables inner classes coursetro. com
static blocks methods imports variables inner classes coursetro. com
static blocks methods imports variables inner classes coursetro. com
blocks
blocks
static blocks methods imports variables inner classes coursetro. com

methods

static blocks methods imports variables inner classes coursetro. com

imports

static blocks methods imports variables inner classes coursetro. com

variables

inner
inner

classes

R e c t a n g l e r = new Rectangle(); //I was

Rectangle r = new Rectangle();

//I was called

Rectangle r2 = new Rectangle();

//I was called

class Rectangle{

double length;

double breadth;

Rectangle(){

…println(“I was called”);

}

public double calculateArea(){…};

}

How many rectangles?

Keep track of the number of rectangles created…

R e c t a n g l e r = new Rectangle(); //1 Rectangle

Rectangle r = new Rectangle();

//1

Rectangle r2 = new Rectangle();

//1

class Rectangle{

double length;

double breadth;

int count = 0;

Rectangle(){

count = count + 1;

}

public double calculateArea(){…};

}

The Normal Way

 

length

0

Rectangle r = new Rectangle();

r

R e c t a n g l e r = new Rectangle(); r breadth 0

breadth

0

 

count

1

length

0

Rectangle r2 = new Rectangle();

r2

R e c t a n g l e r 2 = new Rectangle(); r2 breadth

breadth

0

 

count

1

The Static Way

Rectangle r = new Rectangle();

Rectangle r2 = new Rectangle();

Rectangle r3 = new Rectangle();

r

r2

r3

 

length

0

breadth 0

breadth

0

length 0

length

0

breadth

0

length

0

breadth 0

breadth

0

count

32 1

R e c t a n g l e r = new Rectangle(); //1 Rectangle

Rectangle r = new Rectangle();

//1

Rectangle r2 = new Rectangle();

//2

class Rectangle{

double length;

double breadth;

static int count = 0;

Rectangle(){

count = count + 1;

}

public double calculateArea(){…};

}

…main(String[] args){

println(Rectangle.count);

}

class Rectangle{

double length;

double breadth;

static int count = 0;

Rectangle(){

count = count + 1;

}

public double calculateArea(){…};

}

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

Static Blocks

class Rectangle{

static int count = 0;

Rectangle(){ count = count + 1;

}

}

class Rectangle{

}

static int count; static{

count = 0;

}

Rectangle(){ count = count + 1;

}

Load

class

Load class Initialize static variables Run static blocks Run construc tor Other stuff coursetro. com

Initialize

static

variables

Load class Initialize static variables Run static blocks Run construc tor Other stuff coursetro. com

Run

static

blocks

Load class Initialize static variables Run static blocks Run construc tor Other stuff coursetro. com

Run

construc

tor

Load class Initialize static variables Run static blocks Run construc tor Other stuff coursetro. com

Other

stuff

Static Methods

Methods common to everyone…

main() length 0 r breadth 0 count 3 int getCount () void setCount (int) …main(String[]

main()

main() length 0 r breadth 0 count 3 int getCount () void setCount (int) …main(String[] args){
length 0 r breadth 0
length
0
r
breadth
0

count

3

int

getCount()

void

setCount(int)

…main(String[] args){

println(Rectangle.getCount());

Rectangle.setCount(0);

length 0 r2 breadth 0 length 0 r3 breadth 0
length
0
r2
breadth
0
length
0
r3
breadth
0

}

What about main?

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

Click To Watch Videos Below

Constructors And Overloading Explained Constructors And Overloading Example Relevant
Constructors
And Overloading
Explained
Constructors
And Overloading
Example
Relevant
Explained Constructors And Overloading Example Relevant Videos Static Keyword Explained Static Keyword Example
Videos Static Keyword Explained Static Keyword Example
Videos
Static Keyword
Explained
Static Keyword
Example

Google It!

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

How did I make constants so far?

public class Workday{

static final String MONDAY

static final String TUESDAY

static final String WEDNESDAY

static final String THURSDAY

static final String FRIDAY

}

= “Monday”;

= “Tuesday”;

= “Wednesday”;

= “Thursday”;

= “Friday”;

How did I use them?

public class Schedule {

//Can be Workday.MONDAY, Workday.TUESDAY

String workday;

}

What is an enumeration?

A set of related constants…

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…

How to make one

enum PizzaSize { SMALL, MEDIUM, LARGE, EXTRA_LARGE

};

enum Workday { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY

};

How to use one?

class Schedule {

Workday workday;

public Workday getWorkday(){ return workday;

}

public void setWorkday(Workday day){

}

workday = day;

}

Using enumeration with an if condition

if( schedule.getWorkday() == Workday.FRIDAY ) {

}

println(“Let\’s

party guys!”);

Using enumeration with switch

switch( schedule.getWorkday() ) { case MONDAY: case TUESDAY: case WEDNESDAY: case THURSDAY:

}

…println(“Boring man!”);

break;

case FRIDAY:

println(“Let\’s

break;

party guys!”);

Printing all the enumeration values

for ( Workday w : Workday.values() ) { …println(w.name());

}

Add object oriented stuff

public enum Workday {

MONDAY

(“Monday”),

TUESDAY

WEDNESDAY

THURSDAY

(“Tuesday”),

(“Wednesday”),

(“Thursday”),

FRIDAY

(“Friday”);

final String representation;

Workday (String rep) { representation = rep;

}

public String getRepresentation() { return representation;

}

}

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

…println(w.getRepresentation());

}

Direct Input?

valueOf()… covered in the practical video of this topic.

Google It!

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

Scope vs. Lifetime

Scope : the region in the program where variable is accessible Lifetime : the duration that a variable exists

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

Static Variables

class Test {

static String a = “Test”;

public void display(){ …println(a);

}

public static void setA(String t){

}

a = t;

//Test

}

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); println(Test.a);

}

Test.a = a;

}

//Parameter’s value //Test

Disjoint Scopes

class Test { public void square(double number){

double result = …

}

public void cube(double number){

double result =

}

}

Instance Variables

class Test {

String b = ”Test”;

public void display(){ …println(b);

}

public void setB(String t){

}

b = t;

//Test

}

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

}

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

one b “Test” “Hi”
b
b

“Test”“Hi”

“Hi”

two

two b “Bye” “Test”
b
b

“Bye”

“Test”“Bye”

three

three b “Vow” “Test”
b
b
“Vow” “Test”
“Vow” “Test”
this
this

This & constructors

Covered in the practical session J

Click To Watch Videos Below

Enumeration Enumeration Explained Example
Enumeration
Enumeration
Explained
Example
Videos This Keyword and variable hiding explained This keyword and variable hiding example
Videos
This Keyword
and variable
hiding explained
This keyword
and variable
hiding example

Google It!

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

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

Truck

Wheels

Wheels

Fuel

Fuel

Capacity

Capacity

Weight

Weight

• Mileage

•Mileage

• Seater

•Seater

capacity

Capacity

• Gears

•Gears

• Type

•Type

• Storage

•Storage

capacity

capacity

•Load

capacity

Why Inheritance?

Stop repeating yourself, try to find common stuff and declare them only once…

With Inheritance

Person

First Name

Last Name

Age

With Inheritance Person First Name Last Name Age Employee Occupation Salary Manager Department Managing

Employee

Occupation

Salary

Name Last Name Age Employee Occupation Salary Manager Department Managing Director Experience Branch

Manager

Department

Name Age Employee Occupation Salary Manager Department Managing Director Experience Branch coursetro. com

Managing Director

Experience

Branch

With Inheritance

Vehicle

Wheels

Fuel Capacity

Weight

Mileage

Vehicle Wheels Fuel Capacity Weight Mileage Bike Seater Capacity Gears Car Type Storage Capacity

Bike

Seater Capacity

Gears

Fuel Capacity Weight Mileage Bike Seater Capacity Gears Car Type Storage Capacity Truck Load Capacity

Car

Type

Storage Capacity

Fuel Capacity Weight Mileage Bike Seater Capacity Gears Car Type Storage Capacity Truck Load Capacity

Truck

Load 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.

The Shape Hierarchy

Shape
Shape
The Shape Hierarchy Shape Rectangle Square Circle Triangle coursetro. com
The Shape Hierarchy Shape Rectangle Square Circle Triangle coursetro. com
The Shape Hierarchy Shape Rectangle Square Circle Triangle coursetro. com
The Shape Hierarchy Shape Rectangle Square Circle Triangle coursetro. com
The Shape Hierarchy Shape Rectangle Square Circle Triangle coursetro. com

Rectangle

The Shape Hierarchy Shape Rectangle Square Circle Triangle coursetro. com
Square
Square
Circle
Circle
The Shape Hierarchy Shape Rectangle Square Circle Triangle coursetro. com

Triangle

Shape and Rectangle

class Shape{ public void display(){ …println(“Displaying shape”);

}

}

class Rectangle extends Shape {

double length;

double breadth;

}

class Square extends Rectangle{

double side;

}

s

s display()

display()

 

display()

r

 

lengthr   0.0

0.0

 

breadth

0.0

sq

display()

0.0

0.0

0.0

length display() r   length 0.0   breadth 0.0 sq display() 0.0 0.0 0.0 breadth side coursetro.

breadth

side

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

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

Google It!

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

What is Method Overriding?

To change what the superclass method does, define it in your subclass and override it

Shape, Rectangle and Square

class Shape{ public double getArea(){

}

}

return 0.0;

class Rectangle extends Shape {

double length;

double breadth;

}

class Square extends Rectangle{

double side;

}

s

getArea()

getArea()

length

0.0

breadth

0.0

getArea()

length

0.0

breadth

0.0

side

0.0

() length 0.0 breadth 0.0 side 0.0 r sq returns 0.0 returns 0.0 returns 0.0 s

r

() length 0.0 breadth 0.0 side 0.0 r sq returns 0.0 returns 0.0 returns 0.0 s

sq

() length 0.0 breadth 0.0 side 0.0 r sq returns 0.0 returns 0.0 returns 0.0 s

returns 0.0

returns 0.0

returns 0.0

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

Method Overriding

class Shape{ public double getArea(){

}

return 0.0;

}

class Rectangle extends Shape {

double length;

double breadth;

public double getArea(){ return length * breadth;

}

}

s getArea() returns 0.0 getArea() returns l * b r length 0.0 breadth 0.0
s
getArea()
returns 0.0
getArea()
returns l * b
r
length
0.0
breadth
0.0

s = Shape, r = Rectangle objects

Method Overriding

class Rectangle extends Shape { double length; double breadth; public double getArea(){ return length * breadth;

}

}

class Square extends Rectangle{

double side;

public double getArea(){ return side * side;

}

}

getArea() returns l * b r length 0.0 breadth 0.0 getArea() returns side * side
getArea()
returns l * b
r
length
0.0
breadth
0.0
getArea()
returns side * side
length
0.0
sq
breadth
0.0
side
0.0

r = Rectangle, sq = Square objects

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

Constructor Chaining

class Shape{

Shape(){

…println(“First”); }}

class Rectangle extends Shape {

Rectangle(){ …println(‘’Second”); }}

class Square extends Rectangle{

Square(){

…println(‘Third”); }}

s

extends Rectangle{ Square(){ …println(‘Third”); }} s r sq First First Second First Second Third s =
extends Rectangle{ Square(){ …println(‘Third”); }} s r sq First First Second First Second Third s =
extends Rectangle{ Square(){ …println(‘Third”); }} s r sq First First Second First Second Third s =
r
r

sq

Rectangle{ Square(){ …println(‘Third”); }} s r sq First First Second First Second Third s = Shape,
Rectangle{ Square(){ …println(‘Third”); }} s r sq First First Second First Second Third s = Shape,

First

First

Second

First

Second

Third

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

Super

keyword

Access superclass variable

Call superclass method

Call superclass constructor

How to call superclass variable?

class Shape{

String name = “I am a shape”;

}

class Rectangle extends Shape {

String name = “I am a rectangle”;

public void display(){

…println(name);

}

}

println(super.name);

s name name r display()
s
name
name
r
display()

s = Shape, r = Rectangle objects

I am a shape

I am a rectangle

I am a shape

How to call superclass method?

class Shape{

public void display(){

…println(“Which shape?”);

}

}

class Rectangle extends Shape {

}

@Override

public void display(){

super.display();

…println(“Rectangle”);

}

display(){ super.display (); …println(“Rectangle”); } s r display() display() Which shape Which shape Rectangle s

s

r

display()

display()

(); …println(“Rectangle”); } s r display() display() Which shape Which shape Rectangle s = Shape, r
(); …println(“Rectangle”); } s r display() display() Which shape Which shape Rectangle s = Shape, r

Which shape

Which shape Rectangle

s = Shape, r = Rectangle objects

How to call superclass constructors?

class Shape{