0% found this document useful (0 votes)
20 views

VB_Lecture_3

The document discusses access and non-access modifiers in Java, detailing four access modifiers (private, default, public, protected) that control visibility, and several non-access modifiers (static, final, abstract, synchronized, transient, volatile, strictfp) that provide additional functionalities. It explains the use of the final keyword to restrict modifications to classes, methods, and variables, and the static keyword for memory management and class-level access. The document also covers polymorphism, typecasting (upcasting and downcasting), and abstraction using abstract classes and methods.

Uploaded by

ayabahaa
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)
20 views

VB_Lecture_3

The document discusses access and non-access modifiers in Java, detailing four access modifiers (private, default, public, protected) that control visibility, and several non-access modifiers (static, final, abstract, synchronized, transient, volatile, strictfp) that provide additional functionalities. It explains the use of the final keyword to restrict modifications to classes, methods, and variables, and the static keyword for memory management and class-level access. The document also covers polymorphism, typecasting (upcasting and downcasting), and abstraction using abstract classes and methods.

Uploaded by

ayabahaa
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/ 81

Lecture [3]

Dr. Gehad Ismail Sayed


Access And Non-Access Modifiers In
Java
Java provides two types of modifiers.
⚫ One is Access Modifiers and another one is Non-
Access Modifiers.

⚫ Access modifiers are used to control the visibility of a


class or a variable or a method or a constructor.

⚫ Where as non-access modifiers are used to provide


other functionalities other than the visibility like
synchronizing a method or block.
Access And Non-Access Modifiers In
Java
There are 4 different access modifiers are available in
Java.
⚫ Private: private members of a class, whether it is a field
or a method or a constructor, can not be accessed
outside the class in which they are defined.
⚫ Default: default members or members with no access
modifier are visible within the package. And they are
inherited to only sub classes which reside in the same
package.
⚫ Public: public members are visible everywhere and they
are inherited to any sub class.
⚫ Protected: the scope of the protected modifier is limited
within the package and all subclasses.
Access And Non-Access Modifiers In
Java
Non-access modifiers are those keywords that do not
have anything related to the level of access but they
provide a special functionality when specified.
1. static

2. final

3. abstract

4. synchronized

5. transient

6. volatile

7. Strictfp
Final Keyword
⚫ Java final keyword is a non-access specifier
that is used to restrict a class, variable, and
method.
⚫ If we initialize a variable with the final keyword, then
we cannot modify its value.
⚫ If we declare a method as final, then it cannot be
overridden by any subclasses.
⚫ If we declare a class as final, we restrict the other
classes to inherit or extend it. In other words, the final
classes can not be inherited by other classes.
Final Keyword
Final Variables in Java

• The normal variable and final variable differ only by one parameter that we can
change the value of a normal variable once assigned, but we cannot change the
value of a final variable once assigned.
• Therefore, we must use the final variables only for the assigning values that we
want to remain constant throughout the execution of the program.
Final Keyword
Final Methods in Java Compile Time Errors are those
errors which prevent the code
from running because of an
incorrect syntax such as a
missing semicolon at the end of
a statement or a missing
bracket, class not found

• The above example of the Final Method generates a compile-time error.


• As the Parent class Final method was overridden by the Child class Final
method; that is not possible in the Java programming language.
• The purpose of creating the final methods is to restrict the unwanted
and improper use of method definition while overriding the method.
Final Keyword
Final Classes in Java

Java final class can’t be extended by other classes in the


inheritance. If another class attempts to extend the final class,
then there will be a compilation error.
Static Keyword
Static variable in Java
• In Java, static keyword is mainly used for memory management. It
can be used with variables, methods, blocks and nested classes.
• It is a keyword which is used to share the same variable or method of
a given class. Basically, static is used for a constant variable or a
method that is same for every instance of a class.
Static Keyword
Static variable in Java

Memory became more efficient


Static Keyword
Static variable in Java
To access it, just write ClassName.VariableName
Static Keyword
Static variable in Java
Where is the problem?
Static Keyword
Static variable in Java
Solution: When you declare a variable as static,
then a single copy of the variable is created and
divided among all objects at the class level.
Static Keyword
Static method in Java
Similar to static variables, static methods can also be invoked
using the class name.
Static Keyword
Static method in Java
• Static members belong to the class instead of a specific
instance, this means if you make a member static, you can
access it without object.
• Here we have a static method myMethod(), we can call this
method without any object because when we make a member
static it becomes class level.
• If we remove the static keyword and make it non-static then
we must need to create an object of the class in order to call it.
class SimpleStaticExample{
static void myMethod(){ System.out.println("myMethod");}
public static void main(String[] args){ myMethod(); }
}
Static Keyword
Static class in Java
• A class can be made static only if it is a nested class.
• Nested static class doesn’t need reference of Outer class
• A static class cannot access non-static members of the
Outer class A static nested class may be instantiated without instantiating its outer class.
Inner classes can access both static and non-static members of the outer class.

A static class can access only the static members of the outer class
Static Keyword
Static class in Java
class JavaExample{
private static String str = "BeginnersBook";
static class MyNestedClass{
public void disp() {
/* If you make the str variable of outer class, non-static then you will get compilation
error because: a nested static class cannot access non- static members of the outer class */
System.out.println(str); } }
public static void main(String args[]){
/* To create instance of nested class we didn't need the outer class instance
but for a regular nested class you would need to create an instance of outer class
first */
JavaExample.MyNestedClass obj = new JavaExample.MyNestedClass();
obj.disp(); } }
Strictfp Keyword
• By default, the floating-point computations in Java are
platform-dependent. And so, the floating-point outcome's
precision depends on the hardware in-use.
• Strictfp is used in java for restricting floating-point
calculations and ensuring the same result on every platform
while performing operations in the floating-point variable.
Strictfp Keyword
strictfp modifier is used with classes, interfaces, and
methods only but is not applicable to apply with abstract
methods, variables or constructors.
⚫ class – All code in the class (instance, variable, static
initializers), and code in nested classes will use strictfp
computations.
⚫ method – All code within method will use strictfp
computations.
⚫ interface – All code in any class that implements the
interface will use strictfp computations.
Strictfp Keyword
strictfp modifier is used with classes, interfaces, and
methods only but is not applicable to apply with abstract
methods, variables or constructors.
strictfp class A{} //strictfp applied on class
strictfp interface M{} //strictfp applied on interface
class A{ strictfp void m(){} //strictfp applied on method }
class B{ strictfp abstract void m(); //Illegal combination of
modifiers }
class B{ strictfp int data=10; //modifier strictfp not allowed
here }
class B{ strictfp B(){} //modifier strictfp not allowed here }
Transient Keyword
⚫ The transient keyword in Java is used to avoid
serialization.
⚫ Examples: Customer SSN or password need not to be stored.
⚫ Serialization is the process of converting an object into a
byte stream, and deserialization is the opposite of it.
⚫ When we mark any variable as transient, then that
variable is not serialized.
⚫ Since transient fields aren't present in the serialized form
of an object, the deserialization process would use the
default values for such fields when creating an object
out of the serialized form.
Transient Keyword
Transient Keyword
Transient Keyword
Notes:
⚫ Transient keyword or modifier is applicable only
for variables
⚫ transient and static: Since static fields are not
part of state of the object, there is no use/impact
of using transient keyword with static variables.
However there is no compilation error.
⚫ transient and final: final variables are directly
serialized by their values, so there is no
use/impact of declaring final variable as transient.
There is no compile-time error though.
Recap – OOP Concepts
⚫ Polymorphism is derived from two Greek
words: poly and morphs. The word “poly”
means many and “morphs” means forms. So,
polymorphism means many forms.

⚫ Polymorphism uses a single type entity


(method, operator or object) to represent
different operations (types) in different
scenarios.
Recap – OOP Concepts
⚫ We can achieve polymorphism in Java using the
following ways:
1. Method Overriding
⚫ If the same method is present in both the
superclass and the subclass. Then, the method in
the subclass overrides the same method in the
superclass.
⚫ These methods must have the same method
signature. It means that method name, number of
arguments, order of arguments, and type of
arguments should be an exact match.
Recap – OOP Concepts
⚫ We can achieve polymorphism in Java using the
following ways:
1. Method Overriding
⚫ It is used to change the behavior of existing
methods, to provide fine-grained implementations
in subclasses for methods defined in a
superclass.
⚫ This is an example of runtime time (dynamic
method dispatch or late binding)
2. Method Overloading
Polymorphism
Rules of Method Overriding
⚫ There must be an inheritance relationship

⚫ The method must have the same as in the


parent class
⚫ The method must have the same parameter as
in the parent class.
Polymorphism - Overriding
Polymorphism - Overriding
Polymorphism - Overriding
Recap – OOP Concepts
⚫ We can achieve polymorphism in Java using the
following ways:
1. Method Overriding

2. Method Overloading
⚫ When we have one or more methods with the
same name and/or return types but different
parameter lists (different signatures)
▪ void func() { ... }
▪ float func(double a) { ... }
▪ float func(int a, float b) { ... }
⚫ This is an example of compile time (static
polymorphism or early binding)
Recap – OOP Concepts
⚫ We can achieve polymorphism in Java using the
following ways:
1. Method Overriding

2. Method Overloading
⚫ The overloaded methods must have different
method signatures.
▪ It means that the methods must differ in at least one
of these: number of parameters, type of parameters,
and order of parameters, but should have the
same name
▪ The return type of overloaded methods may or
may not have the same return type
Polymorphism - Overloading
Polymorphism - Overloading
If we have a restaurant deals with MAC and KFS, so we
will have different type of the order.
Polymorphism - Overloading
Advantages of method overloading
⚫ Increases the readability of the program
⚫ Example:
⚫ Instead of implementing order1, order 2, and order 3
Polymorphism - Overloading
Advantages of method overloading
⚫ Increases the readability of the program
⚫ Example:
⚫ Add contact to the list in mobile phone application
Polymorphism
Can we override a static method?
Polymorphism
Can we override a static method?

NO

Note:
Upcasting!
Upcasting and Downcasting in
Java
⚫ A process of converting one data type to another is
known as Typecasting.
⚫ Upcasting and Downcasting is the type of object
typecasting.
⚫ Upcasting
⚫ The process of casting an object of child class to the parent class
is called Upcasting.
⚫ Upcasting can be done implicitly or explicitly.
⚫ Upcasting will reduce the choice of methods, we can use on the
type casted object.
⚫ However, for overridden methods, static or dynamic binding
comes into play, and it will decide the method implementation to
use.
Upcasting and Downcasting in
Java
class SuperClass
{
public void print()
{ System.out.println("Printing from SuperClass");}
}
class Child extends SuperClass
{
String name;
Child(String s){ this.name = s; }
@Override
public void print() { System.out.println("Printing from Child class");}

public void printName(){ System.out.println(this.name); }


}
Upcasting and Downcasting in
Java
What will be the output?

public static void main(String[] args)


{
Child c = new Child("child");
c.print();
//Implicit Upcasting
SuperClass s2 = new Child("Second Child");
s2.print();
}
Upcasting and Downcasting in
Java
What will be the output?

public static void main(String[] args)


{
Child c = new Child("child");
c.print();
//Implicit Upcasting
SuperClass s2 = new Child("Second Child");
s2.print(); //print() method of Child class is called due to dynamic binding
}
Upcasting and Downcasting in
Java
We can also explicitly cast the object, but it is not really required.
public static void main(String[] args)
{
Child c = new Child("child");
c.print();
//Explicit Upcasting
SuperClass s2 = (SuperClass) new Child("Second Child");
s2.print(); //print() method of Child class is called due to dynamic binding
}
Upcasting and Downcasting in
Java
Upcasting will narrow our choices of methods. For example, after
upcasting a Child class object to SuperClass, we can no longer
use the printName() method of the Child class. We will get a
compilation error.
public static void main(String[] args)
{
SuperClass s = new Child("First Child");
s.printName();//Error
}
Upcasting and Downcasting in
Java
⚫ Downcasting
⚫ Downcasting can be considered as the reverse of Upcasting.
⚫ We are typecasting an object of the parent class to the child
class.
⚫ Unlike upcasting, downcasting is not done implicitly by the
compiler.
public class TypeCastingDemo
{
public static void main(String[] args)
{
SuperClass s = new Child("First Child");
s.printName(); //Error
}
}
Upcasting and Downcasting in
Java
⚫ Downcasting
public class TypeCastingDemo
{ public static void main(String[] args){
SuperClass s = new Child("First Child");
s.printName(); //Error}
}
Solution
public class TypeCastingDemo
{ public static void main(String[] args){
SuperClass s = new Child("First Child");
((Child) s ).printName();
//Downcasting from SuperClass to Child class.}
}
Recap – OOP Concepts
Abstract Classes and Methods
⚫ Data abstraction is the process of hiding certain details
(methods/features) and showing only essential
information to the user.
Abstraction
Example:
Login in Facebook or twitter, …
Abstraction
Example:
We can use API without knowing how this happened
Abstraction
Types of Abstraction:
⚫ Data Abstraction

⚫ Control Abstraction

Abstraction can be achieved with either


1. Abstract classes (Partial Abstraction 0 to 100%)

2. Interface (Fully Abstraction 100%)


Abstraction
Abstract Classes and Methods
⚫ The abstract keyword is a non-access modifier,
used for classes and methods:
⚫ Abstract class:
⚫ It allows you to create blueprints for concrete classes (is
a class that has an implementation for all of its methods)
⚫ It is a restricted class that cannot be used to create objects
(to access it, it must be inherited from another class).
⚫ An abstract class can have both abstract and regular
methods (non-abstract)
⚫ Abstract method: can only be used in an abstract
class, and it does not have a body. The body is
provided by the subclass (inherited from).
Abstraction
Rules for Abstract Class
⚫ An abstract class must be declared with an
abstract keyword.
⚫ It can have abstract and non-abstract
methods.
⚫ It cannot be instantiated.

⚫ It can have final methods which will force the


subclass not to change the body of the method.
⚫ It can have constructors and static methods
also.
Abstraction
Abstract Classes
Abstraction
Abstract Classes
Abstraction
Abstraction - Example

Error
Abstraction - Example

Solution
Abstraction - Example
Abstract class is written in
italic format in UML class
diagram
Swing - Inheritance Hierachy
Swing - Containers
1. JFrame
2. JPanel: it is a container that can be used in
both applications and applets
⚫ Panel, like all containers, can contain both visual
components and other containers.
3. JApplet: It is a special type of program that
is embedded in the webpage to generate the
dynamic content. It runs inside the browser
and works at client side.
Jpanel vs. JFrame
JPanel JFrame
Parent class javax.swing.JComponent java.awt.Frame
What is it? A specific area for A window for hosting
putting in GUI standalone
components and applications, like an
operations. alert window or
notification window.
Title Bar There is no title bar. It contains a title bar.
Weight Light Heavy
Contain Multiple GUI It is the window; it can
components and have one or more
operations, but isn’t a JPanel instances
window. inside it
JFrame - Example
FrameDemo.Java

NewClass.Java
JPanel - Example
FrameDemo.Java

NewClass.Java
JPanel - Example
Swing - Examples
Question: Write a program that creates five instances of
JButtons dynamically using the inheritance concept. The
output of the program must be as follows.
Hint
The window size is 400x400
Answer
FrameDemo.Java
Answer

NewClass.Java
Swing - Examples
Question: Write a program that creates 15 instances of
JButtons dynamically using the inheritance concept. The
output of the program must be as follows.
Hint
The window size is 400x400
Answer
FrameDemo.Java

NewClass.Java
Swing - Layouts
Do we always have to use layout managers?
No, it is also possible not to use any layout manager and to
place components manually. This is known as absolute
positioning.
To convert to absolute positioning, it is done in 3 steps;
1. Specify the layout manager to be null

2. Add the component to the holder in the normal way

3. Use setBounds() method to place and size the


component in the holder.
Swing - Layouts
Absolute Positioning
⚫ Advantage:
you get greater control over placement.
⚫ Disadvantage:
⚫ Every element has to be placed manually, rather than
relying on a layout manager.
⚫ This can have major ramifications when you have to
change the user interface; for example, inserting a
new element will mean that many of existing elements
will need to be moved.
JPanel - Example
Question: Write a program to add two buttons within a
panel. The output of the program must be as follows.
Hint
1. Use Color.GRAY, Color.green, Colo.yellow for the
background colors
2. The window size is 400x400

3. The panel size 200x200 staring from (0,100)


Answer
The default layout for panel
is FlowLayout

Null layout means


absolute positioning -
you have to do all the
work in your code. No
layout manager to help
you out.
JPanel - Example
Question: Write a program to add two buttons within a
panel using the inheritance concept. The output of the
program must be as follows.
Hint
1. Use Color.GRAY, Color.green, Colo.yellow for the
background colors
2. The window size is 400x400

3. The panel size 200x200 staring from (0,100)


Answer
FrameDemo.Java

NewClass.Java
JPanel - Example
Question: What is the output of the following program?
Answer
Question: What is the output of the following program?
JPanel - Example
Question: What is the output of the following program?
Answer
Question: What is the output of the following program?
81

You might also like