0% found this document useful (0 votes)
43 views161 pages

CTIS 222 Week 8 Review On OO and Java

The document outlines key concepts in Object Oriented Analysis and Design (OOAD) for a Spring 2024-2025 course, focusing on programming versus learning algorithms, Java concepts, and memory management. It includes definitions and examples of programming, algorithms, IDEs, variable categories, and access modifiers in Java. The document also addresses common questions and answers related to Java programming, such as interfaces, inheritance, and variable scope.

Uploaded by

toprakalt2002
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views161 pages

CTIS 222 Week 8 Review On OO and Java

The document outlines key concepts in Object Oriented Analysis and Design (OOAD) for a Spring 2024-2025 course, focusing on programming versus learning algorithms, Java concepts, and memory management. It includes definitions and examples of programming, algorithms, IDEs, variable categories, and access modifiers in Java. The document also addresses common questions and answers related to Java programming, such as interfaces, inheritance, and variable scope.

Uploaded by

toprakalt2002
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 161

CTIS 222 Object Oriented

Analysis and Design (OOAD)


Spring 2024-2025
Week 8
Review on OO and Java Concepts
Today
• Differentiate Programming vs. Learning
Algorithms
• Q&As – Interview Questions
– OO and Java concepts
– etc.
–…
Programming
• Q: What are the instructions for reaching from Bilkent
to Kızılay?
• A:
– Turn right
– Drive 1.5 km.
– Turn left
– ...etc.
• Programming is using
– the right statement,
– in the right order
– using the right syntax

Source: Foundations of Programming (3 courses)\1 - Fundamentals\1 - Programming Basics


Programming
• Q: What are the instructions for reaching from Bilkent
to Kızılay?
• A:
– Turn right
– Drive 1.5 km.
– Turn left
– ...etc.
• Programming is using
– the right statement,
by coding an algorithm in a PL
– in the right order
– using the right syntax Specific to a PL

Source: Foundations of Programming (3 courses)\1 - Fundamentals\1 - Programming Basics


Learning vs. Programming
• To solve a problem on a computer, an algorithm is
required.
• An algorithm is a sequence of instructions that are
carried out to transform the input to the output.
– Ex: An algorithm for sorting.
– Input: a set of numbers
– Output: their ordered list
– For sorting, there may be various algorithms.
• the most efficient one
• with the least # of instructions, memory, or both
• etc..
Source: Ethem Alpaydin-Machine Learning. The New AI 2017
Learning vs. Programming
• For some problems, however, it is NOT easy to find
an algorithm.
– predicting customer behavior
– differentiating spam e-mails from legitimate ones
– Input: an e-mail text message
– Output: True/False (whether the message is spam or not)
• But we do NOT know how to transform the input to
the output.
• What is considered spam changes over time and from
individual to individual.

Source: Ethem Alpaydin-Machine Learning. The New AI 2017


Learning vs. Programming
• For some problems, however, it is NOT easy to find
an algorithm.
– predicting customer behavior
– differentiating spam e-mails from legitimate ones
• We would like the computer (the machine) to
extract automatically the algorithm for this task.
• There is no need to learn to sort numbers (we already have
algorithms for that), but there are many applications for
which we do not have an algorithm but have lots of
data. by machine learning algorithms
Source: Ethem Alpaydin-Machine Learning. The New AI 2017
Writing your source code…
• Q: How do you write your source code (file)?
• A: Plaintext
– Using a text editor like notepad
• Q: We usually write our code using a Programmer's Text
Editors. Why?
• A: We need some features like
– Line #s
– Automatic Colour coding
– Syntax checking
– etc.
IDE
• Q: What is an IDE? Have you experienced it before?
Any Examples?
• A: Integrated Development Environment
– Text editor +
• build automation tools
• a debugger
• refactoring
• version control
• code search
• visual programming
• attitudes across different computing platform
– Examples: VisualStudio, Eclipse
Programming Languages
High-Level Language
(Easy to learn)
Javascript
Ruby/Python
Java, C#
Objective C
C++
C Low-Level Language
(Hard to learn)
Assembly Language
Machine Code
CPU
Source: Foundations of Programming (3 courses)\1 - Fundamentals\1 - Programming Basics
Multitasking vs. Multithreading
• Q: What is multitasking? What is multitherading?

• Multi-tasking • Multi-threading

• When your OS can • Doing multiple


run multiple things (tasks)
programs @ the inside the same
same time. program.
Strong-typed vs. Loose-typed Languages
• Q: What is the difference between strong-
typed and lose-typed PL?

• Strong-typed • Loose-typed
int x; var x;
OR
$x;
For More Info: "The C programming language" Kernighan, Brian W.
Parameters vs. Arguments
• Q: What is the difference between a parameter
and an argument?
• A:

Parameter
Argument
function addTwoNumbers(a,b){ ...
... addTwoNumbers(5,7);
//function code goes here
...
...
}
Source: Foundations of Programming (3 courses)\1 - Fundamentals\1 - Programming Basics
Memory Management
• Q: What is memory leakage? And what is
dangling reference?
• A:
• Memory Leakage
– When you forget to release the unused object(s).
• Dangling Reference
– When you attempt to reach the object you already
released.
Memory Management

Javascript, ActionScript Automatic (Slower)


Ruby/Python
Java, C#, VB. Net Garbage Collection (Batch)
Objective C Reference Counting
C++
C
Assembly Language Manual (Faster but tedious & difficult)
Machine Language
CPU
Source: Foundations of Programming (3 courses)\1 - Fundamentals\1 - Programming Basics
Q & A?
• Q: In Java, can we develop an OO application
written within a single class segment?
• A: DEPENDS. An OO Java app is supposed to be
composed of many separate class segments.
It is the essence of OO.
Q & A?
• Q: In Java, objects are runtime concepts. They do
not exist if you do not run the application. TRUE
or FALSE?
• A: TRUE

Car Class  Template


Q & A?
• Q: What is an interface in Java?
• A:
– An interface in Java is a blueprint of a behavior.
• List of abstract methods
1. It is used to achieve abstraction.
2. By interface, we can support the functionalty of
multiple inheritance.
3. It can be used to achieve loose coupling.
Q & A?
• Q: In Java, an interface must be written within
a file and must be saved with an .interface
extension. TRUE or FALSE?
• A: FALSE
Q & A?
• Q: In Java, whenever a class implements an
interface, that class MUST implement the
methods defined in the interface. TRUE or
FALSE?
• A: TRUE
Q & A?
• Q: In Java, a class may have only one parent
class but may have as many interfaces as it
wishes. TRUE or FALSE?
• A: TRUE
– A Java class can only extend one parent class.
Multiple inheritance is NOT allowed.
Q & A?
• Q: In Java, an abstract class’s methods
cannot be non-abstract (concrete). That is,
every method of an abstract class must be
abstract. TRUE or FALSE?
• A: FALSE
Q & A?
• Q: In Java, there are four types of access
modifiers (visibilities)?
• A: TRUE
Modifiers in Java
Visibilities of attributes in Java
(Access Modifiers)

package visibility default in Java protected visibility  visible to


subclasses regardless of the package
Q & A?
• Q: How we can achieve {read-only} and
{write-only} in Java?
// {read-only} Cat Class
//{write-only} Cat Class
// no setters
// no getters
public class Cat {
public class Cat {
private String name;
private String name;
private int age;
private int age;
public void setName(String na) {
public String getName() {
this.name = na;
return name;
}
}
public void setAge(int age) {
public int getAge() {
this.age = age;
return age;
}
}
}
}
Q & A?
• Q: Can we have a sub-package under an existing
Java package?
• A: Yes.
Visibilities…
public static void main(String[] args)
{
//statements go here
}

• If you use the keyword public that makes the method


accessible to other objects.
• If you use the keyword private, the method cannot be
invoked by other objects.

Source: Premchand S. Nair-Java Programming Fundamentals Problem Solving Through Object Oriented Analysis and Design 2008
Visibilities…
public static void main(String[] args)
{
//statements go here
}

• The keyword static refers to the fact that method main is


shared by all objects belonging to the class.

Source: Premchand S. Nair-Java Programming Fundamentals Problem Solving Through Object Oriented Analysis and Design 2008
Valid vs. Invalid – Why/not?

String word;
word = System.out.println("Hello World");

• Invalid.
• The method println is a void method and cannot appear in
an assignment statement.

Source: Premchand S. Nair-Java Programming Fundamentals Problem Solving Through Object Oriented Analysis and Design 2008
Valid vs. Invalid – Why/not?

String word = "Try me!";


word.charAt(1);

• Invalid. (Might not be run/compile-time errors)


• The method charAt is a value returning method. The returned
value 'r' is lost.

Source: Premchand S. Nair-Java Programming Fundamentals Problem Solving Through Object Oriented Analysis and Design 2008
Categories of variables
• In Java, there are 4 categories of variables.
– instance variables
declared at class level
– static variables
– parameter variables
declared at block level
– local variables
• A block is a sequence of statements enclosed within a pair of
braces { and }.

Source: Premchand S. Nair-Java Programming Fundamentals Problem Solving Through Object Oriented Analysis and Design 2008
Categories of variables
char nextCharacter;
int totalGamesPlayed;
double stateTaxRate = 6.85;
String nextLine = "Have a close look at me!";

• This statement instructs the compiler to allocate 2 bytes of memory


and no value is stored.
• Further, the memory location will be known as nextCharacter in
the program and can be modified so long as the modified value is of
type char.

Source: Premchand S. Nair-Java Programming Fundamentals Problem Solving Through Object Oriented Analysis and Design 2008
Categories of variables
char nextCharacter;
int totalGamesPlayed;
double stateTaxRate = 6.85;
String nextLine = "Have a close look at me!";

• This statement instructs the compiler to allocate 4 bytes of memory.


• The memory location will be known as totalGamesPlayed in
the program and can be modified as long as the modified value is of
data type int.

Source: Premchand S. Nair-Java Programming Fundamentals Problem Solving Through Object Oriented Analysis and Design 2008
Categories of variables
char nextCharacter;
int totalGamesPlayed;
double stateTaxRate = 6.85;
String nextLine = "Have a close look at me!";

• This statement allocates 8 bytes and stores 6.85 as the initial


value.
• The memory allocated will be known in the program as
StateTaxRate.

Source: Premchand S. Nair-Java Programming Fundamentals Problem Solving Through Object Oriented Analysis and Design 2008
Categories of variables
char nextCharacter;
int totalGamesPlayed;
double stateTaxRate = 6.85;
String nextLine = "Have a close look at me!";
• This statement is quite different from the other three statements.
• This is due to the fact that String is a class in Java and not a primitive data type.
In the case of classes, the only variables you can declare are reference variables.
• Now a reference variable is one that can keep the reference of an object.
• A memory location is allocated and labeled as nextLine. However, memory
location nextLine does not contain the String "Have a close look at me!".
Instead, the String is stored somewhere else in memory and the reference of the
String is kept in the reference variable nextLine.

Source: Premchand S. Nair-Java Programming Fundamentals Problem Solving Through Object Oriented Analysis and Design 2008
Categories of variables
char nextCharacter;
int totalGamesPlayed;
double stateTaxRate = 6.85;
String nextLine = "Have a close look at me!";

Source: Premchand S. Nair-Java Programming Fundamentals Problem Solving Through Object Oriented Analysis and Design 2008
Scope of variables
• An instance variable is available only within the
object (if it is declared private).
• A local variable is available only within the block
from its point of declaration.
• A formal parameter is available within the
method.

Source: Premchand S. Nair-Java Programming Fundamentals Problem Solving Through Object Oriented Analysis and Design 2008
Scope of variables
• formal parameter — the identifier used in a
method to stand for the value that is passed
into the method by a caller.
• amount is a formal parameter of pDeposit

• actual parameter — the actual value that is


passed into the method by a caller.
• 200 used when pDeposit is called is an actual parameter.
• actual parameters are often called arguments
public void pDeposit( int amount )
{
balance = balance + amount ;
}
The formal parameter…
public static void main(String[] args)
{
//statements go here
}

• A list of formal parameters is enclosed within a pair of


parentheses.
• The formal parameter list in this case is String[] args. (Array)
• The pair of parentheses enclosing the formal parameter cannot be
omitted.
Source: Premchand S. Nair-Java Programming Fundamentals Problem Solving Through Object Oriented Analysis and Design 2008
Existence of variables
• An instance variable exists as long as the associated
object exists.
• A local variable is created every time declaration
statement is executed during the method
execution and the variable ceases to exist upon the
completion of the block it is declared.
• A formal parameter is created at the beginning of
the method invocation and it ceases to exist upon
the completion of the method.
Source: Premchand S. Nair-Java Programming Fundamentals Problem Solving Through Object Oriented Analysis and Design 2008
Named constant
• There are certain values in an app that need NOT be
modified during the program execution.
– Ex: To work, one must be at least 16 years old.
– Ex: A conversion formula that converts pounds into
kilogram must make use of the fact that 1lb is 0.454 kg.
• During the program execution, these data values
need to be guarded against accidental changes.
• Java allows you to allocate memory using a named
constant and store a data value.
– The value of a named constant remains fixed during the
program execution.
Source: Premchand S. Nair-Java Programming Fundamentals Problem Solving Through Object Oriented Analysis and Design 2008
Named constant
• In Java, you can declare a named constant in 2
different contexts:
• Class level:
public static final char PERCENTAGE = '%';
public static final int MAX_ALLOWED_WEIGHT=40;

• Method level:
final float ERROR_ALLOWED = 0.01F;
final double POUND_TO_KILOGRAM = 0.454;

Source: Premchand S. Nair-Java Programming Fundamentals Problem Solving Through Object Oriented Analysis and Design 2008
Named constant
[public][static] final dataType IDENTIFIER = literal;
final dataType IDENTIFIER = literal;

• The word static specifies that only one memory


location will be allocated to all instances of a class
and such a memory location will be available even
if there is no object belonging to the class.
• Observe that the word static is optional.
However, from a programming point of view, there
is no need to have multiple copies of a constant
value.
• The reserved word final indicates that the literal
stored in the IDENTIFIER is final, or cannot be
changed.
Source: Premchand S. Nair-Java Programming Fundamentals Problem Solving Through Object Oriented Analysis and Design 2008
Named constant
public class TestFinalAttribute2 {
final String myText= "111";
public static void main(String[] args) {
TestFinalAttribute2 obj = new TestFinalAttribute2();
obj.letUsPrint();
}
public void letUsPrint () {
System.out.println(myText);
}
public void changeClassFinal () {
myText="Try to Change";
}
public void changeMethodFinal () { output with errors:
final String myText2= "222"; -------------------
myText2="Try to Change"; 111
}
}
Named constant
public class TestFinalAttribute2 {
final String myText= "111";
public static void main(String[] args) {
TestFinalAttribute2 obj = new TestFinalAttribute2();
obj.letUsPrint();
}
public void letUsPrint () {
System.out.println(myText);
}
public void changeClassFinal () {
myText="Try to Change";
}
public void changeMethodFinal () { output with errors:
final String myText2= "222"; -------------------
myText2="Try to Change"; 111
}
}
Named constant - Error
public class TestFinalAttribute2 {
final String myText= "111";
public static void main(String[] args) {
TestFinalAttribute2 obj = new TestFinalAttribute2();
obj.letUsPrint();
}
public void letUsPrint () {
System.out.println(myText);
}
public void changeClassFinal () {
myText="Try to Change";
}
public void changeMethodFinal () {
final String myText2= "222";
myText2="Try to Change";
}
}
Packages
• In Java, classes are grouped/organized into packages.
• Most commonly used classes are in the package
java.lang and this package is available to all
programs.
• This is accomplished by placing an import
statement in the beginning of the source program:
import java.util.*;
// imports java.util package

Source: Premchand S. Nair-Java Programming Fundamentals Problem Solving Through Object Oriented Analysis and Design 2008
System.out.println("Hello World");

• System is static class from java.lang


package(default package in java) and cannot be
instantiated
• out is a reference variable defined in System
also it is a final variable
• println() is the method used to print on
standard output.
– println()/print() are overloaded methods
from PrintStream class.
Application-Specific Methods
• In general, every class needs accessor methods
and mutator methods for every instance variable.
– Accessor method: A method that does NOT modify
any instance variable of an object is called an accessor
method.
– A mutator method: All other methods are known as
mutator methods.
• In addition, it is a good idea to include the
accessor method toString.
Accessor methods (a.k.a. getter methods)
• Here, we provide the accessor methods that
return the value of an instance variable of the
Stock class.
public int getNumberOfShares()
{
return numberOfShares;
} class Stock
{
private int numberOfShares;
private String tickerSymbol;
private double dividend;
}

Source :Premchand S. Nair-Java Programming Fundamentals Problem Solving Through Object Oriented Analysis and Design, 2008
Accessor methods
• Here, we provide the accessor methods that
return the value of an instance variable of the
Stock class.
public double yearlyDividend()
{
double totalDividend;
totalDividend = numberOfShares * dividend;
return totalDividend;
class Stock
} {
private int numberOfShares;
private String tickerSymbol;
private double dividend;
}
Source :Premchand S. Nair-Java Programming Fundamentals Problem Solving Through Object Oriented Analysis and Design, 2008
Mutator methods (a.k.a. setter methods)
• A method that changes the value of one or more instance
variables is called a mutator method.
• Here, we develop a mutator methods of the Stock class
to set the number of shares.
public void setNumberOfShares(int inNumberOfShares)
{
numberOfShares = inNumberOfShares;
}
class Stock
{
private int numberOfShares;
private String tickerSymbol;
private double dividend;
}
Source :Premchand S. Nair-Java Programming Fundamentals Problem Solving Through Object Oriented Analysis and Design, 2008
toString METHOD
The toString method returns a String that contains essential
information. Observe that toString is an accessor method that returns a
String.
Ex: We assume that for a stock, the most essential information is the
number of shares currently owned and the stock symbol.
class Stock
{
private int numberOfShares;
private String tickerSymbol;
public String toString() private double dividend;
{ }
String str;
str = numberOfShares + " " + tickerSymbol;
return str;
}

Source :Premchand S. Nair-Java Programming Fundamentals Problem Solving Through Object Oriented Analysis and Design, 2008
Object declaration and creation
Stock testStock = new Stock();
• The left-hand side of the above assignment
statement declares a reference variable
testStock of the type Stock.
• The right-hand side creates a new object
belonging to the Stock class and returns the
reference.

Source :Premchand S. Nair-Java Programming Fundamentals Problem Solving Through Object Oriented Analysis and Design, 2008
Object declaration and creation
Stock testStock; //(2)
testStock = new Stock(); //(3)
• Statement 2 declares a local variable
testStock.
• Statement 3 creates a new instance of Stock
and initializes the reference variable
testStock with the reference of the newly
created instance returned by the new operator.
• In other words, Statement 3 instantiates the local
variable testStock.

Source :Premchand S. Nair-Java Programming Fundamentals Problem Solving Through Object Oriented Analysis and Design, 2008
Method Invocation
• Here, we assume that all the methods
introduced are public, value returning, and
predefined.
1.static methods that have no parameters.
2.static methods that have parameters.
3. Methods that are not marked as static and
have no parameters.
4. Methods that are not marked as static and
have parameters.

Source :Premchand S. Nair-Java Programming Fundamentals Problem Solving Through Object Oriented Analysis and Design, 2008
Method Invocation
• Here, we assume that all the methods
introduced are public, value returning, and
predefined.
1.static methods that have no parameters.
number = 1 + (int) (10 * Math.random());

Source :Premchand S. Nair-Java Programming Fundamentals Problem Solving Through Object Oriented Analysis and Design, 2008
Method Invocation
• Here, we assume that all the methods
introduced are public, value returning, and
predefined.
1.static methods that have no parameters.
2.static methods that have parameters.
number = 10 * (int) Math.ceil(17.4999);

Source :Premchand S. Nair-Java Programming Fundamentals Problem Solving Through Object Oriented Analysis and Design, 2008
Method Invocation
• Here, we assume that all the methods
introduced are public, value returning, and
predefined.
1.static methods that have no parameters.
2.static methods that have parameters.
3. Methods that are not marked as static and
have no parameters.
number = 10 * strOne.length();

Source :Premchand S. Nair-Java Programming Fundamentals Problem Solving Through Object Oriented Analysis and Design, 2008
Method Invocation
• Here, we assume that all the methods
introduced are public, value returning, and
predefined.
1. static methods that have no parameters.
2. static methods that have parameters.
3. Methods that are not marked as static and
have no parameters.
4. Methods that are not marked as static and
have parameters.
ch = strOne.charAt(3);

Source :Premchand S. Nair-Java Programming Fundamentals Problem Solving Through Object Oriented Analysis and Design, 2008
Method Overloading (a.k.a. static polymorphism)
• In Java, method name need NOT be unique.
• There can be many methods all having the
same name.
• The PL feature that allows the programmer to
create more than one method within a class
having the same name.
• public int indexOf(char ch)
• public int indexOf(String str)
• public int indexOf(char ch, int s)
• public int indexOf(String str, int s)

Source :Premchand S. Nair-Java Programming Fundamentals Problem Solving Through Object Oriented Analysis and Design, 2008
Q & A?
• Q: Can we have one class in another class in
Java?
• A: Yes.
class OuterClass {
...
static class StaticNestedClass {
...
}
class InnerClass {
...
}
}
Q & A?
public class A {
public static void main(String[] args) {
B myB = new B();
myB.run();
}
}
Saved as a
class B{ single Java file
int x;  A.java
int y;
String z;

void run() {
System.out.println("I am running");
}
}
A: True

Source: Udemy, java-object-oriented-programming-build-a-quiz-application


Primitive vs. Reference Type
public class PrimitiveVsReferenceType {

public static void main(String[] args) {

int x = 7;
String obj = "xyzt";

System.out.println(x);
System.out.println(obj);
}
}

Source: Udemy, java-object-oriented-programming-build-a-quiz-application


Primitive type in Java
• The Java PL supports 8 primitive data types.
• A primitive type is predefined by the
language and is named by a reserved
keyword.
• Primitive values do NOT share state with
other primitive values.

Source: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
Primitive type in Java
Data Type Default Value (for fields)

1 byte 0

2 short 0

3 int 0

4 long 0L

5 float 0.0f

6 double 0.0d

7 char '\u0000'

8 boolean false

Source: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
Primitive type in Java
• Java primitive types examples:
–int and double
• Adapters are sometimes called
wrappers.
• The Java wrapper classes Integer,
Float, Double etc. are adapters for
the Java primitive types.

Source: Object-Oriented Software Engineering Practical software development using UML and Java, 2nd Edt., Timothy C. Lethbridge and Robert Laganière, 2005
Variables of Primitive & Reference Types
• Every variable represents a memory location that
holds a value.
• When you declare a variable, you are telling the
compiler what type of value the variable can hold.
– For a variable of a primitive type, the value is of the
primitive type.
– For a variable of a reference type, the value is a
reference to where an object is located.

Source: Introduction to Java Programming, Comprehensive Version, Y. Daniel Liang, 2014.


Variables of Primitive & Reference Types

Source: Introduction to Java Programming, Comprehensive Version, Y. Daniel Liang, 2014.


Java and Memory
• All Java apps reside in main memory (MM).
• The MM is usually divided into many sections.
• Here, we concentrate only the heap and stack.
• All objects in Java are always stored in the heap.
• All the object references and the local variables
are stored in stack.

Source: Udemy, java-object-oriented-programming-build-a-quiz-application


Java and Memory

0X556677

Heap
0X35AADE

Triangle_obj Square_obj
 0X556677  0X35AADE Stack

Source: Udemy, java-object-oriented-programming-build-a-quiz-application


Memory Locations
Memory

Stack

Source: Source: Udemy Master Object Oriented Design in Java - Homework + Solutions
Memory Locations
Memory
main(){

Stack
When you hit the
run button, the first
method invocation is First Frame main()
main()

Source: Source: Udemy Master Object Oriented Design in Java - Homework + Solutions
Memory Locations
Memory
main(){
int a;

Stack
When you hit the
run button, the first
method invocation is a ?
First Frame main()
main()

Source: Source: Udemy Master Object Oriented Design in Java - Homework + Solutions
Memory Locations
Memory
main(){
int a;
a=15;

Stack
When you hit the
run button, the first
method invocation is a 15
First Frame main()
main()

Source: Source: Udemy Master Object Oriented Design in Java - Homework + Solutions
Memory Locations
Memory
main(){
int a;
a=15;
DoMethod();

Second Frame DoMethod(); ? Stack


DoMethod() b
{ a 15
int b; First Frame main()

Source: Source: Udemy Master Object Oriented Design in Java - Homework + Solutions
Memory Locations
Memory
main(){
int a;
a=15;
DoMethod();

Second Frame DoMethod(); ? Stack


DoMethod() b
{ a 15
int b; First Frame main()

Swim()

}
Source: Source: Udemy Master Object Oriented Design in Java - Homework + Solutions
Memory Locations
Memory
main(){
int a;
a=15;
DoMethod();

Third Frame Swim()


}

Second Frame DoMethod(); ? Stack


DoMethod() b
{ a 15
int b; First Frame main()

Swim()

}
Source: Source: Udemy Master Object Oriented Design in Java - Homework + Solutions
Memory Locations
Memory
main(){
int a; Swim() method is removed
a=15; from the stack
DoMethod();

Third Frame

}
Second Frame DoMethod(); ? Stack
DoMethod() b
{ a 15
int b; First Frame main()

Swim();
When Swim() method is
executed completely
}
Source: Source: Udemy Master Object Oriented Design in Java - Homework + Solutions
Memory Locations
Memory
main(){
int a;
a=15; DoMethod() method is
DoMethod(); removed from the stack

When DoMethod() method


Third Frame
is executed completely
}
Second Frame Stack
DoMethod()
{ a 15
int b; First Frame main()

Swim();

}
Source: Source: Udemy Master Object Oriented Design in Java - Homework + Solutions
Memory Locations
Memory
main(){
int a;
a=15;
DoMethod();

Course myC = new Course();

Stack
}
a 15
First Frame main()

Source: Source: Udemy Master Object Oriented Design in Java - Homework + Solutions
Memory Locations
Memory
main(){
int a;
a=15;
DoMethod();

Course myC = new Course();

Stack
}
a 15
First Frame main()
myC XYZ

XYZ Course Heap

Source: Source: Udemy Master Object Oriented Design in Java - Homework + Solutions
Memory Locations – Instance Variable
Memory
// Outside the main
class A {
//instance variable
int xyz;
...
}

Stack

A myA = new A ();


First Frame main()myA 0xaadd

0xaadd A Heap
xyz
Source: Source: Udemy Master Object Oriented Design in Java - Homework + Solutions
Memory Locations – Instance Variable
Memory
// Outside the main
class A {
//instance variable
int xyz;
...
}

Stack

A myA = new A ();


myA.xyz = 8; First Frame main()myA 0xaadd

0xaadd A Heap
xyz 8
Source: Source: Udemy Master Object Oriented Design in Java - Homework + Solutions
Memory Locations – Instance Variable
Memory
// Outside the main
class A {
//instance variable Stack
main()
int xyz;
First Frame myA 0xaadd
...
myA2 0xbcdd
}

A myA = new A ();


myA.xyz = 8;
A myA2 = new A (); A
xyz ?
0xbcdd
Heap
0xaadd A
xyz 8
Source: Source: Udemy Master Object Oriented Design in Java - Homework + Solutions
Memory Locations – Instance Variable
Memory
// Outside the main
class A {
//instance variable Stack
main()
int xyz;
First Frame myA 0xaadd
...
B myB; myA2 0xbcdd
} myB1 0xeeff

B
A myA = new A (); 0xeeff
myA.xyz = 8;
A xyz ?
A myA2 = new A ();
B myB1 = new B(); 0xbcdd myB Heap
?

0xaadd A xyz 8
myB ?
Source: Source: Udemy Master Object Oriented Design in Java - Homework + Solutions
Memory Locations – Instance Variable
Memory
// Outside the main
class A {
//instance variable Stack
main()
int xyz;
First Frame myA 0xaadd
...
B myB; myA2 0xbcdd
} myB1 0xeeff

B
A myA = new A (); 0xeeff
myA.xyz = 8;
A xyz ?
A myA2 = new A ();
B myB1 = new B(); 0xbcdd myB Heap
?
myA.myB = myB1;
0xaadd A xyz 8
myB 0xeeff
Source: Source: Udemy Master Object Oriented Design in Java - Homework + Solutions
this reference
• Objects are stored in the heap.
– Inside the objects: Only the variables are stored not
the methods.
• There is only one copy of the method. A method
is shared by all the objects.
– Method body  Permanent Generation space of
heap

Source: Udemy, java-object-oriented-programming-build-a-quiz-application


Output:
public class ThisReference {
this reference x --> 4
y --> 5
x --> 6
public static void main(String[] args) {
B myB = new B();
y --> 7
myB.method1(4, 5);
myB.method2();
Question: There is only one method. How
B otherB = new B(); does this method operate on different
otherB.method1(6, 7); objects?
otherB.method2();
} Answer: Every non static method has a
} this reference variable associated with it.
class B{
int x;
int y; void method1(int v1, int v2) {
void method1(int v1, int v2) { this.x= v1;
x= v1; this.y= v2;
y= v2; }
}
// automatically prepended
void method2() {
System.out.println("x --> " + x);
System.out.println("y --> " + y);
}
}
Source: Udemy, java-object-oriented-programming-build-a-quiz-application
Q & A?
• Q: Can we have overloaded constructors in Java?
• A: Yes.
Overloaded Constructors
public class OverloadedConstructors {
public static void main(String[] args) {
Default One with no parameters
B myB = new B();
B myB1 = new B(1,2);
Constructor with two parameters invoked
B myB3 = new B(3,4,"Ali");} v1 --->1
} v2 --->2
class B{ Constructor with three parameters invoked
int x; v1 --->3
int y;
v2 --->4
String z;
B() {
v3 --->Ali
System.out.println("Default One with no parameters");}

B(int v1, int v2) {


System.out.println("Constructor with two parameters invoked");
System.out.println("v1 --->" + v1);
System.out.println("v2 --->" + v2);}

B(int v1, int v2, String v3) {


System.out.println("Constructor with three parameters invoked");
System.out.println("v1 --->" + v1);
System.out.println("v2 --->" + v2);
System.out.println("v3 --->" + v3);}
} Source: Udemy, java-object-oriented-programming-build-a-quiz-application
Constructors
• Q: Is it possible to call a constructor from
another constructor?
• A: TRUE. But you should use the this()
constructor.

Source: Udemy, java-object-oriented-programming-build-a-quiz-application


public class ThisConstructor {
this () constructor Default One with no parameters
public static void main(String[] args) { Constructor with two parameters invoked
B myB4 = new B(1,2); v1 --->1
B myB5 = new B(3,4,"Ali");}
v2 --->2
}
class B{
Default One with no parameters
int x; Constructor with two parameters invoked
int y; v1 --->8
String z; v2 --->9
B() { Constructor with three parameters invoked
System.out.println("Default One with no parameters");}v1 --->3
B(int v1, int v2) { v2 --->4
this(); // MUST BE IN THE FIRST LINE v3 --->Ali
System.out.println("Constructor with two parameters invoked");
System.out.println("v1 --->" + v1);
System.out.println("v2 --->" + v2);}
B(int v1, int v2, String v3) {
this(8,9); // MUST BE IN THE FIRST LINE
System.out.println("Constructor with three parameters invoked");
System.out.println("v1 --->" + v1);
System.out.println("v2 --->" + v2);
System.out.println("v3 --->" + v3);}
}

Source: Udemy, java-object-oriented-programming-build-a-quiz-application


Q & A?
• Q: Can an interface extend another interface
in Java?
• A: Yes. For example Java Collections Framework.
– When an interface is extended, it inherits all the
previous methods.
Java Collections Framework
Q & A?
• Q: Can an interface extend multiple interfaces
in Java?
• A: Yes. A Java class can only extend one parent
class. Multiple inheritance is not allowed.
Interfaces are not classes, however, and an
interface can extend more than one parent
interfaces.
Int1 IntN

Int
public interface Printable { public interface Writable {
void print(); void write();
} }

public interface Notable extends Printable, Writable {


void note();
}

public class Main implements Notable{


public void print(){System.out.println("Print");}
public void write(){System.out.println("Write");}
public void note(){System.out.println("Note");}

public static void main(String args[]){


Main obj = new Main();
obj.print();
obj.write();
obj.note();}
}
Printable Writable
<<interface>> <<interface>>

Notable
<<interface>>

Main
Q & A?
• Q: Can an abstract class implements an
interface in Java?
• A: Yes.
Q & A?
• Q: Can an abstract class implements an
interface in Java? OUTPUT:
print in concrete class A

• A: Yes. methodPersonOnly in concrete class A


onlyAbstractClass

public abstract class Person implements printable { public class client {


public static void main(String[] args) {
abstract public void methodPersonOnly(); Person myA = new A();
myA.print();
public void onlyAbstractClass() { myA.methodPersonOnly();
System.out.println("onlyAbstractClass"); myA.onlyAbstractClass();
} }
} }

public interface printable { public class A extends Person {


void print(); @Override
void onlyAbstractClass(); public void print() {
} System.out.println("print in concrete class A");
}
public void methodPersonOnly() {
System.out.println("methodPersonOnly in concrete class A");
}
}
Wrap-Up
class C1 implements I3 {
interface I1 {
int member1;
double m5();
C2 member2;
void m6();
static int member3;
}
void m1() {... int j=5; ... }
static void m2() {... }
} interface I2 {
void m7();
float m8();
interface I3 extents I1, I2{
abstract class C2 {
int member4; }

void m9();
abstract void m3();
void m4() {... } }
}

class C3 extents C2{ class C4 extents C2{


boolean member5; char member6;

void m3() {... } void m3() {... }

} }
Q & A?
• Q: Is it necessary that a given class must
implement ALL the methods declared in the
interfaces?
• A: Yes.
Q & A?
• Q: Can an interface extend a class in Java?
• A: No.
– If this was the case, a method’s body should have
implemented within that interface . This violates
the interface definition.
Q & A?
• Q: Can an interface contain a constructor in
Java?
• A: No.
Q & A?
• Q: Can you create an instance of an interface
in Java?
• A: No.
Q & A?
• Q: Can an interface contain instance fields
in Java?
• A: No. 
Q & A?
• Q: Can an interface contain non-abstract
(concrete) methods in Java?
• A: No. 
Q & A?
• Q: Can an interface be given the private
access modifier?
• A: No. Then the interface could never be
used
– All abstract, default, and static methods
in an interface are implicitly public, so you
can omit the public modifier.
• The Java compiler adds
– public and abstract keywords before the
interface method.
– public, static and final keywords before
data members.
Q & A?
• Q: Can an interface contain the following
type of members in Java?
– public, static, final fields (i.e., constants)
– default and static methods with bodies
• A: Yes.
Common Uses of interfaces
• Interfaces are flexible things and can be used for
many purposes in Java:
– Specifying minimal functional requirements for classes
(This is its principal purpose.)
– A work-around for Java’s lack of multiple inheritance.
– For defining groups of related symbolic constants.
(This is a somewhat unexpected use, but is not
uncommon.)
Using Interfaces for Symbolic
Constants
• In addition to containing method declarations,
interfaces can contain constants, that is,
variables that are public final static.
interface OlympicMedal {
static final String GOLD = "Gold";
static final String SILVER = "Silver";
static final String BRONZE = "Bronze";
}

• Considered bad practice.


Default Method in Java Interfaces
I1
<<interface>>

m1() Cn
m2() m1() // concrete
m3() m2() // concrete
m3() // concrete

C1 C2
m1() // concrete m1() // concrete
m2() // concrete m2() // concrete
m3() // concrete m3() // concrete
Default Method in Java Interfaces
I1
<<interface>>

m1() Cn
m2() m1() // concrete
m3() m2() // concrete
m4() m3() // concrete

m4() // concrete

C1 C2
m1() // concrete m1() // concrete
m2() // concrete m2() // concrete
m3() // concrete m3() // concrete
m4() // concrete m4() // concrete
Default Method in Java Interfaces
I1
<<interface>>

m1() Cn
m2() m1() // concrete
m3() m2() // concrete
default m4()//concrete m3() // concrete

C1 C2
m1() // concrete m1() // concrete
m2() // concrete m2() // concrete
m3() // concrete m3() // concrete
Default Method in Java Interfaces
• Java 8 introduces “Default Method”, a new feature
– Add new methods to the interfaces without
breaking the existing implementation of these
interface.

public interface A {
public void m1();
default public void m2 {
...
println("default m2");
B b = new B();
}
b.m2(); // print "default m2"
}
...
public class B implements A
{
public void m1() {…}
}
Why default keyword is introduced
in interfaces?
• Suppose we need to add a new method in an
existing interface.
• Obviously the old code will not work as the
classes have not implemented those new
methods.
• So with the help of default implementation,
we will give a default body for the newly added
functions. Then the old codes will still work.
Why default keyword is introduced in interfaces?
public interface I1 {
void m1(); Example 1
}

public interface I2 {
void m2();
}

public class Main implements I1,I2{


public static void main(String args[]){
Main obj = new Main();
obj.m1();
obj.m2();}
public void m1() {
System.out.println("method 1 of Main class");}
public void m2() {
System.out.println("method 2 of Main class");}
}
Output:
method 1 of Main class
method 2 of Main class
Why default keyword is introduced in interfaces?
public interface I1 {
void m1(); Example 1
default void m3(){
System.out.println("method 3 of I1");}}
public interface I2 {
void m2();
default void m4(){
System.out.println("method 4 of I12");}}
public class Main implements I1,I2{
public static void main(String args[]){
Main obj = new Main(); Output:
obj.m1(); method 1 of Main class
obj.m2(); method 2 of Main class
obj.m3(); method 3 of I1
obj.m4();} method 4 of I12
public void m1() {
System.out.println("method 1 of Main class");}
public void m2() {
System.out.println("method 2 of Main class");}}
Multiple Inheritance Ambiguity Problems
public interface I1 {
void m1(); Example 2
default void m3(){
System.out.println("method 3 of I1");}}
public interface I2 {
void m2();
default void m4 m3(){
System.out.println("method 4 of I12");}}
public class Main implements I1,I2{
public static void main(String args[]){
Main obj = new Main();
obj.m1();
obj.m2();
obj.m3();
obj.m4();}
public void m1() {
System.out.println("method 1 of Main class");}
public void m2() {
System.out.println("method 2 of Main class");}}
Multiple Inheritance Ambiguity Problems
• Since java class can implement multiple interfaces
and each interface can define default method with
same method signature, therefore, the inherited
methods can conflict with each other.
public interface A { public interface B {
default int m1(){ default int m1(){
return 1;} return 2; }
} }
Example 3
public class Main implements A, B {
public int m1() {
return 3;}
public static void main(String[] args) { Output:
Main myMain = new Main(); 3
System.out.println(myMain.m1());}
}
Multiple Inheritance Ambiguity Problems
• Since java class can implement multiple interfaces
and each interface can define default method with
same method signature, therefore, the inherited
methods can conflict with each other.
public interface A { public interface B {
default int m1(){ default int m1(){
return 1;} return 2; }
} } Example 4

public class Main implements A, B {


public int m1() {
return 3;}
public static void main(String[] args) {
Main myMain = new Main();
System.out.println(myMain.m1());}
}
Multiple Inheritance Ambiguity Problems
• Since java class can implement multiple interfaces
and each interface can define default method with
same method signature, therefore, the inherited
methods can conflict with each other.
public interface A { public interface B {
default int m1(){ default Boolean m1(){
return 1;} return true;}
} }

public class Main implements A, B {


public int m1() {
return 3;} Example 5
public static void main(String[] args) {
Main myMain = new Main();
System.out.println(myMain.m1());}
}
Multiple Inheritance Ambiguity Problems
• Since java class can implement multiple interfaces
and each interface can define default method with
same method signature, therefore, the inherited
methods can cannot
The class conflict implement
with each other.
two interfaces in
java that have methods
public interface A { with same
public interface B { name but
default int m1(){ default Boolean m1(){
return 1;} different return
return type.
true;}
} }

public class Main implements A, B {


public int m1() {
return 3;} Example 5
public static void main(String[] args) {
Main myMain = new Main();
System.out.println(myMain.m1());}
}
Abstract classes vs. Interfaces
• After introducing Default method, it seems
that interfaces and abstract classes are
same.
– However, they are still different concept in Java 8.
• Abstract class can define constructor. They can
have a state associated with them.
• default method can be implemented only in the
terms of invoking other interface methods, with
no reference to a particular implementation's
state.
Abstract classes vs. Interfaces
• So the question arises why use interfaces when
we have abstract classes?
• The reason is, abstract classes may contain
non-final variables, whereas variables in
interface are final, public and static.
static methods in interfaces
• Another feature that was added in JDK 8 is that
we can now define static methods in
interfaces which can be called independently
without an object.
– Note: these methods are not inherited.
interface in1 {
final int a = 10;
static void display(){
System.out.println("hello");} Output :
} hello

class testClass implements in1 {


public static void main (String[] args){
in1.display();}
}
Q & A?
• Q: Multiple inheritance is not supported through
class in java, but it is possible by an interface,
why?
• A: Multiple inheritance is not supported in the
case of class because of ambiguity. However, it is
supported in case of an interface because there is
no ambiguity. It is because its implementation is
provided by the implementation class.
Example
interface Printable{
void print();
}
interface Showable{
void print();
}

class TestInterface3 implements Printable, Showable{


public void print(){System.out.println("Hello");}
public static void main(String args[]){
TestInterface3 obj = new TestInterface3();
obj.print();}
}
Output:
Hello
To Wrap Up
• The relationship between classes and
interfaces:
Q & A?
Q: An abstract class is ONLY meant to be a
parent class for another class?
A: TRUE

Source: Source: Udemy Master Object Oriented Design in Java - Homework + Solutions
Q & A?
Q: A local variable is not accessible outside the
block it is declared. Therefore, no access
modifier is required for a local variable?
A: TRUE
Q & A?
Q: An instance variable exists as long as the
associated object exists.
A local variable is created every time declaration
statement is executed during the method
execution and the variable ceases to exist upon
the completion of the block it is declared.
A: TRUE
Static methods vs Instance methods in Java
Static methods vs Instance methods in Java
• Instance method are methods which require an
object of its class to be created before it can be
called.
• To invoke a instance method, we have to create
an Object of the class in within which it defined.

Source: https://www.geeksforgeeks.org/static-methods-vs-instance-methods-java/
Static methods vs Instance methods in Java
• Memory allocation: These methods themselves
are stored in Permanent Generation space of
heap but the parameters (arguments passed to them) and
their local variables and the value to be returned
are allocated in stack.
– They can be called
• within the same class in which they reside OR
• from the different classes defined either in the same
package or other packages
depend on the access type provided to the desired
instance method.
Source: https://www.geeksforgeeks.org/static-methods-vs-instance-methods-java/
Static methods vs Instance methods in Java
• Important Points:
• Instance method(s) belong to the Object of the
class not to the class
– i.e. they can be called after creating the Object of the
class.
• Every individual Object created from the class
has its own copy of the instance method(s) of
that class.
• They can be overridden since they are resolved
using dynamic binding at run time.
Source: https://www.geeksforgeeks.org/static-methods-vs-instance-methods-java/
Static methods vs Instance methods in Java

import java.io.*;
class Foo{
String name = "";
// Instance method to be called within the same class or
// from a another class defined in the same package or in different package.
public void myInstanceMethod(String name){
this.name = name;
}
}
class TestTest{
public static void main (String[] args) {
// create an instance of the class.
Foo ob = new Foo();
// calling an instance method in the class 'Foo'.
ob.myInstanceMethod("222");
System.out.println(ob.name); Output :
} 222
}

Source: https://www.geeksforgeeks.org/static-methods-vs-instance-methods-java/
Static methods vs Instance methods in Java
• Static methods are the methods in Java that can
be called without creating an object of class.
• They are referenced by the class name itself or
reference to the Object of that class.

Source: https://www.geeksforgeeks.org/static-methods-vs-instance-methods-java/
Static methods vs Instance methods in Java
• Memory Allocation: They are stored in
Permanent Generation space of heap as they are
associated to the class in which they reside not to
the objects of that class.
• But their local variables and the passed
argument(s) to them are stored in the stack.
• Since they belong to the class so they can be
called to without creating the object of the class.

Source: https://www.geeksforgeeks.org/static-methods-vs-instance-methods-java/
Static methods vs Instance methods in Java
• Important Points:
• Static method(s) are associated to the class in which
they reside i.e. they can be called even without
creating an instance of the class i.e
ClassName.methodName(args).
• They are designed with aim to be shared among all
Objects created from the same class.
• Static methods can not be overridden. But can be
overloaded since they are resolved using static
binding by compiler at compile time.

Source: https://www.geeksforgeeks.org/static-methods-vs-instance-methods-java/
Static methods vs Instance methods in Java

import java.io.*;
class OOAD{
public static String myName = "";
public static void myStaticMethod(String name){ Output :
myName = name; vaibhav
}
} mohit
class TestTest{
public static void main (String[] args) {
// Accessing the static method myStaticMethod () and field by class name itself.
OOAD. myStaticMethod("vaibhav");
System.out.println(OOAD.myName);
// Accessing the static method myStaticMethod () by using Object's reference.
OOAD.obj = new OOAD();
obj. myStaticMethod("mohit");
System.out.println(obj.myName);
}
}

Source: https://www.geeksforgeeks.org/static-methods-vs-instance-methods-java/
Static variables and their values
• Static variables and their values (primitives or
references) defined in the class are stored
in PermGen space of memory.

Source: https://www.geeksforgeeks.org/static-methods-vs-instance-methods-java/
final keyword in Java
• final keyword is used in different contexts.
• First of all, final is a non-access
modifier applicable only to a attribute, a method
or a class.
• Following are different contexts where final is
used.
– final Attributes  To create constant attributes
– final Methods  To prevent Method overriding
– final Classes To prevent Inheritance
Source: https://www.geeksforgeeks.org/final-keyword-java/
final keyword in Java
• final keyword is used in different contexts.
• First of all, final is a non-access
modifier applicable only to a attribute, a method
or a class.
• Following are different contexts where final is
used.
– final Attributes  To create constant attributes
– final Methods  To prevent Method overriding
– final Classes To prevent Inheritance
Source: https://www.geeksforgeeks.org/final-keyword-java/
final attribute in Java
• When a attribute is declared with final keyword,
its value can’t be modified, essentially, a constant.
– This also means that you must initialize a final
attribute .
• If the final attribute is a reference, this means
that the variable cannot be re-bound to reference
another object, but internal state of the object
pointed by that reference attribute can be changed
i.e. you can add or remove elements from final
array or final collection.
• It is good practice to represent final attribute in ALL
UPPERCASE, using underscore to separate words.
Source: https://www.geeksforgeeks.org/final-keyword-java/
final attribute in Java

public class TestFinalAttribute0 {


final int i; // Not initialized
public static void main(String[] args) {
TestFinalAttribute0 obj = new TestFinalAttribute0();
obj.letUsPrint();
}
public void letUsPrint () {
System.out.println("222 " + i);
}
}

Error:
The blank final field i may not have been
initialized
Source: https://www.geeksforgeeks.org/final-keyword-java/
final attribute in Java

public class TestFinalAttribute0 {


final int i; // Not initialized
public static void main(String[] args) {
TestFinalAttribute0 obj = new TestFinalAttribute0();
obj.letUsPrint();
}
public void letUsPrint () {
System.out.println("222 " + i);
}
}

Output:
222 0
Source: https://www.geeksforgeeks.org/final-keyword-java/
final attribute in Java
public class TestFinalAttribute1 {

public static void main(String[] args) {


final int i = 10;
i = 30; // Error because i is final.
}
}

// In Java, when final keyword is used with a variable of


// primitive data types (int, float, .. etc), value of
// the variable cannot be changed.

Source: https://www.geeksforgeeks.org/final-keyword-java/
final attribute in Java
public class TestFinalAttribute2 {
public static void main(String args[]) {
final OtherClass obj = new OtherClass();
obj.i = 30; // Works
}
}

class OtherClass {
int i = 10;
}

// Note that non-primitive variables are always references to


// objects in Java. Thus, the members of the referred object
// can be changed.

Source: https://www.geeksforgeeks.org/final-keyword-java/
final method in Java
• final keyword is used in different contexts.
• First of all, final is a non-access
modifier applicable only to a attribute, a method
or a class.
• Following are different contexts where final is
used.
– final Attributes  To create constant attributes
– final Methods  To prevent Method overriding
– final Classes To prevent Inheritance
Source: https://www.geeksforgeeks.org/final-keyword-java/
public class TestFinalMethod extends Demo {

public static void main(String[] args){


TestFinalMethod obj = new TestFinalMethod();
obj.m1();
obj.m2();
}
public void m1() {
System.out.println("Concrete m1()");
}
public final void m2(){
System.out.println("Concrete m2()");
}
public void m3(){
System.out.println("Overrriden m3()");
}
} abstract class Demo{
public int a;
public Demo(){
a = 10;
}
Error: abstract public void m1();
overrides final method m2.
abstract public final void m2();
public final void m3() {
System.out.println("Demo m3()");
}
Source: https://www.geeksforgeeks.org/final-keyword-java/
}
public class TestFinalMethod extends Demo {

public static void main(String[] args){


TestFinalMethod obj = new TestFinalMethod();
obj.m1();
obj.m2();
}
public void m1() {
System.out.println("Concrete m1()");
}
public final void m2(){
System.out.println("Concrete m2()");
}
public void m3(){
System.out.println("Overrriden m3()");
}
} abstract class Demo{
public int a;
public Demo(){
Error: a = 10;
final methods can’t }
be overridden. Thus, an abstract public void m1();
abstract public final void m2();
abstract methods public final void m3() {
can’t be final . System.out.println("Demo m3()");
}
}
Source: https://www.geeksforgeeks.org/final-keyword-java/
public class TestFinalMethod extends Demo {

public static void main(String[] args){


TestFinalMethod obj = new TestFinalMethod();
obj.m1();
obj.m2();
}
public void m1() {
System.out.println("Concrete m1()");
}
public final void m2(){
System.out.println("Concrete m2()");
}
public void m3(){
System.out.println("Overrriden m3()");
}
} abstract class Demo{
public int a;
public Demo(){
a = 10;
}
abstract public void m1();
abstract public final void m2();
public final void m3() {
System.out.println("Demo m3()");
}
}
Source: https://www.geeksforgeeks.org/final-keyword-java/
final class in Java
• final keyword is used in different contexts.
• First of all, final is a non-access
modifier applicable only to a attribute, a method
or a class.
• Following are different contexts where final is
used.
– final Attributes  To create constant attributes
– final Methods  To prevent Method overriding
– final Classes To prevent Inheritance
Source: https://www.geeksforgeeks.org/final-keyword-java/
final class in Java
• When a class is declared with final keyword, it is
called a final class.
• A final class cannot be extended (inherited).
• There are two uses of a final class :
• One is definitely to prevent inheritance, as final
classes cannot be extended.
– Ex: All Wrapper Classes like Integer, Float etc. are
final classes. We can not extend them.
• The other use of final with classes is to create an
immutable class like the predefined String class.
– You can not make a class immutable without making it
final.
Source: https://www.geeksforgeeks.org/final-keyword-java/
final class in Java

final public class Parent {


// attributes and methods will go here
}

public class Child extends Parent {


// attributes and methods will go here
}

Source: https://www.geeksforgeeks.org/final-keyword-java/
final class in Java

final public class Parent {


// attributes and methods will go here
}

public class Child extends Parent {


// attributes and methods will go here
}

Source: https://www.geeksforgeeks.org/final-keyword-java/
static vs. final
Basis For static final
Comparison
Applicable keyword is applicable to nested static class, keyword is applicable to class,
variables, methods and block. methods and variables.
Initialization NOT compulsory to initialize the static compulsory to initialize the
variable at the time of its declaration. final variable at the time of
its declaration.
Modification The static variable can be reinitialized. The final variable CAN NOT
be reinitialized.

Methods static methods can only access the final methods can not be
static members of the class, and can only overridden.
be called by other static methods.
Class static methods class’s object can not be final class can not be
created, and it only contains static inherited by any class.
members only.
Block static block is used to initialize the final keyword supports NO
static variables. such block.
static block in Java
class Test {
static int i;
int j;
static {
i = 10;
System.out.println("static block called ");
}
Test(){
System.out.println("Constructor called");
}
}
class Main {
public static void main(String args[]) {

// Although we have two objects, OUTPUT:


// static block is executed only once. static block called
Test t1 = new Test(); Constructor called
Test t2 = new Test(); Constructor called
}
}
Source: https://www.geeksforgeeks.org/final-keyword-java/ Source: https://www.geeksforgeeks.org/g-fact-79/

You might also like