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

3-Lecture3

Java oop lecture 3

Uploaded by

megaacount30360
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

3-Lecture3

Java oop lecture 3

Uploaded by

megaacount30360
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Object-Oriented Programming

Lecture3: Classes - Objects


• Classes
• Objects
• Constructors
• Overloading method
• Access Control
• Static and fixed methods
• Inner Classes
Class
• A class is the template from which objects are
derived. It defines the structure and behavior of the
objects. Classes can contain fields (variables) and
methods (functions).
 Definition: A class is defined using the class
keyword followed by the Class-name.
 Content: Fields to store data, action methods,
and object constructors to initialize objects.
Object
• Object is a state of the class from which this object is
derived. It is similar in some properties to many
objects derived from the same class, so that each
object has a name that distinguishes it from the rest of
the objects.
Cont..
• Creation: Objects are created using the new
keyword followed by the class constructor.
 Identity: Each object has its own identity and
state, defined by the values of its fields.
Properties
• Properties: A group of attributes that change the objects.
Although there are many common Properties between different
objects, each object has a set of Properties (attributes) that
distinguish it from other objects. Examples of properties
include color, address, location, height, width, etc
Methods
• Methods are a set of actions that objects can perform. They are
functions that perform specific functions built within the class
from which the object is derived to perform a specific function
related to the behavior of the object. These functions are
implemented by calling them in the program by writing the
name of the object, then a dot, and then writing the name of
the function.
• Object_namet.function_name
Class Declaration
• A Class is declared using the reserved word class, followed
by the class-name, noting that the class-name must begin
with a capital letter. Then Braces {…..} the class to write
the properties and methods inside it.
class Student{
String name;
• We note that all variables
(properties) defined in the "Student"
int ID;
class cannot be given values ​within
String Dep;
the class itself. Because these
int age; variables do not represent one
String address; student but rather represent a
double avg; general template for all students.
char group; Therefore, the values ​of these
} properties cannot be equal for all
students.
Creating objects of the class:
• To give these property values ​specific to a particular student,
we must first create an object or a group of objects from this
class, each of which represents an object with the same
properties with different values.
• Then we give these property values, each according to the data
type.
• Class_name object_name = new Class_name
Cont…

• Class_name object_name = new class_name();

• This line is written into the main function of the program and
then values ​are given for all properties. By writing the name-
object, then the dot, then name-property, then the assignment
sign "=", then the value of the property according to data type.
• Object_name. name-property = value;
Example: Create an object of a class “Student” in the main
function of another class called “Test”.
class Student{
String name;
int ID;
String Dep;
double avg;
char group;
}
public class Test{
public static void main(String args[]){
Student s1 = new Student();
s1.name="Ali";
s1.ID=52362;
s1.Dep =“IS";
s1.avg=80;
s1.group='c';
}}
public class Test
2. {
3. public static void main(String args[])
4. {
5. Student s1 = new Student(); //Student ‫اشتقاق كان من الفئة‬
: ‫شرح البرنامج‬
6. s1.name=“Ahmed” ‫ تم إنشاء فئة تحت‬14 ‫في السطر‬
7. s1.ID=52362; ‫ تحتوي على مجموعة‬Student ‫اسم‬
‫قيم‬ ‫تخصيص‬
8. s1.Dep=“CS” ‫من الخصائص والتي‬
‫للخصائص‬
9. s1.avg=80;
10. s1.group='c';
‫ ودالة واحدة‬20 ‫ إلى‬16 ‫تبدأ من السطر‬
11. s1.print(s1.name,s1.ID,s1.Dep,s1.avg,s1.group);// ‫ استدعاء دالة الطباعة‬21 ‫ تبدأ من السطر‬print ‫تحت اسم‬
12. } 28 ‫إلى‬
13. } ‫ تم اشتقاق كائن‬5 ‫في السطر رقم‬
14. class Student //Student ‫انشاء الفئة‬
15. {
Student . ‫ من الفئة‬s1 ‫تحت اسم‬
16. String name; ‫ تم فيها تخصيص‬10 ‫ إلى‬6 ‫السطر من‬
.‫قيم لكافة خصائص الكائن‬
‫خصائص‬
17. int ID;
18. String Dep; ‫ تم استدعاء الدالة‬11 ‫في السطر رقم‬
‫الكالس‬
19. double avg;
‫الخاصة بالطباعة وارسال كافة‬
20. char group;
21. void print(String p1,int p2,String p3,double p4,char p5) ‫المعامالت المطلوب طباعة‬
22. { .‫قيمها‬
23. System.out.println("Student name is :" + p1 );
24. System.out.println("Student id is :" + p2 );
25. System.out.println("Student department is :" + p3 );
26. System.out.println("Student average is :" + p4 );
‫دالة الطباعة‬
27. System.out.println("Student group is :" + p5 );
28. }
29. }
Constructor
• constructor is a function statement that has a beginning and an end that is
similar in structure to the function and is distinguished from the rest of the
functions through its name, which is similar to the name of the class in which it
is located.
• The constructor function also differs from other functions in the way it is
implemented, as the code inside it is executed every time a new object is
derived from the class in which the constructor function is located.
• This is done using the keyword "new", which is used when creating a new
object from the class. Also, the constructor function cannot return a value as is
available in some other functions.
• Constructor functions are used to create variables that need to be revalued or
given initial values ​every time a new object of the class is derived. There are
two types of constructor functions:
public class Main_Class // ‫الفئة الرئيسية‬
1. Non Parameterized {
Constructor: public static void main(String[]
args)// ‫الدالة الرئيسة في البرنامج‬
• constructor {
functions that do not Student Std= new Student(); //
Student ‫اشتقاق كائن من الفئة‬
contain parameters Std.print(); // ‫استدعاء دالة الطباعة‬
and therefore do not }
}
need to send class Student // ‫الفئة‬
values ​or variables {
public Student()
when executed. {
There is only one name="Salem"; //name ‫تهيئة المتغير‬
}
function in each public void print()// ‫دالة الطباعة‬
class and it is called {
System.out.println("welcome Mr "+name);
Default Constructor }
}

class_name object_name = new class_name


2. Parameterized Constructor:
constructor functions that contain parameters and
therefore need to send values ​or variables when they
are executed. The programmer can define more than
one constructor function in the same class. But must
take into account that all of these constructors must
have the same class name, provided that they differ in
the number of parameters, their types, or the
arrangement of the types of these parameters to
differentiate between them while calling them. This is
what is known as constructor overloading.

class_name object_name = new class_name(param1, param2 ,....)


The following example shows how to define and call the default
constructor and other parametric constructs:
class Example{
Example() // ‫تعريف‬constructs‫االفتراضي‬
{ System.out.println("Default constructor");
}
Example(int i, int j) // ‫ يحتوي على معاملين‬constructs
{
System.out.print("parameterized constructor");
System.out.println(" with Two parameters");
}
Example(int i, int j, int k) // ‫ يحتوي على ثالثة معامالت‬constructs
{
System.out.print("parameterized constructor");
System.out.println(" with Three parameters");
}
public static void main(String args[]) // ‫الدالة الرئيسية‬
{
Example obj = new Example(); ‫ استدعاء دالة البناء االفتراضية‬//
Example obj2 = new Example(12, 12); //‫ الذي يحتوي على معاملين‬constructs ‫استدعاء‬
Example obj3 = new Example(1, 2, 13); } // ‫الذي يحتوي على ثالث معامالت‬constructs
}
}
Overloading method
Definition:
Method overloading in Java is a feature that
allows a class to have more than one method
with the same name, provided their parameter
lists are different. It can be achieved by:

Changing the number of parameters.


Changing the type of parameters.
Changing both the number and type of
parameters.
Key Points about Method Overloading:
• Different Parameters: Methods must differ in the number or
type of parameters.
• Return Type: The return type can be different, but it alone is
not sufficient for overloading.
• Same Class: The overloaded methods must be in the same
class or inherited from a parent class.
public class MathUtils { //Example of Method Overloading:
// Method to add two integers
public int add(int a, int b) {
return a + b;
}
// Overloaded method to add three integers
public int add(int a, int b, int c) {
return a + b + c;
}
// Overloaded method to add two double values
public double add(double a, double b) {
return a + b;
}
// Overloaded method to add three double values
public double add(double a, double b,
double c) {
return a + b + c;
}
}
Cont..
public class Main {
public static void main(String[] args) {
MathUtils mathUtils = new MathUtils();

System.out.println("Sum of two integers: " + mathUtils.add(10, 20));


System.out.println("Sum of three integers: " + mathUtils.add(10, 20, 30));
System.out.println("Sum of two doubles: " + mathUtils.add(10.5, 20.5));
System.out.println("Sum of three doubles: " + mathUtils.add(10.5, 20.5, 30.5));
}
}

Output
Sum of two integers: 30
Sum of three integers: 60
Sum of two doubles: 31.0
Sum of three doubles: 61.5
Explanation of the previous example
• Method Signatures: In the MathUtils class, the add method is
overloaded with different signatures.

• add(int a, int b)
• add(int a, int b, int c)
• add(double a, double b)
• add(double a, double b, double c)
• Usage: In the Main class, the correct add method is called based on
the number and type of arguments passed.

• mathUtils.add(10, 20) calls add(int a, int b)


• mathUtils.add(10, 20, 30) calls add(int a, int b, int c)
• mathUtils.add(10.5, 20.5) calls add(double a, double b)
• mathUtils.add(10.5, 20.5, 30.5) calls add(double a, double b, double c)
Benefits of Method Overloading:
1. Readability: Using the same method name for
similar operations improves code readability.
2. Consistency: It provides a consistent interface for
methods that perform similar tasks.
3. Convenience: Users can call methods with different
parameters without needing to remember multiple
method names.
Access Control
Access control in Java refers to the mechanisms and policies
that determine the visibility and accessibility of classes,
methods, and variables within the code.
It is enforced through the use of access modifiers which are
keywords that set the level of access for these components.
Access Control
Java provides four primary access modifiers:

Public: The class, method, or variable is accessible from any


other class in any package.
Protected: The class, method, or variable is accessible within
its package and by subclasses, even if the subclass is in a
different package.
Default (Package-Private): If no access modifier is specified,
the class, method, or variable is accessible only within its
package. This means that other classes in the same package can
use it, but classes in different packages cannot.
Private: The class, method, or variable is accessible only within
its class.
Importance of Access Control in Java
Encapsulation: Access control is a core principle of
object-oriented programming (OOP) and helps encapsulate data
and methods. By restricting access to a class's internal state and
implementation details, access control ensures that the class can
only be manipulated in well-defined ways.
Security: Access control mechanisms help prevent
unauthorized access and modification by controlling the
visibility of classes, methods, and variables, enhancing the
application's security.
//To understand the effects of public and private access, consider the following
program:
/* This program demonstrates
the difference between public class AccessTest {
and private. public static void main(String args[])
*/ {
class Test { // default access Test ob = new Test();
// These are OK, a and b may be accessed directly
int a; // public access
ob.a = 10;
public int b; // private access
ob.b = 20;
private int c; // methods to access c // This is not OK and will cause an error
void setc(int i) { ob.c = 100; // Error!
// set c's value // You must access c through its methods
c = i; ob.setc(100); // OK
} System.out.println("a, b, and c: " + ob.a + " " +
int getc() { // get c's value ob.b + " " + ob.getc());
return c; }
} }
}
Explanation: previous example
• The Test class has three instance variables:
• a with default (package-private) access.
• b with public access.
• c with private access.
• Inside AccessTest's main method:
• a and b are accessed directly and assigned values
(ob.a = 10; and ob.b = 20;).
• c cannot be accessed directly (ob.c = 100; would
cause an error), so it is set using the setc method
(ob.setc(100);).
• The values of a, b, and c are printed using their
respective getter methods (ob.getc() for c).
Static and fixed methods
• In Java, static and fixed (non-static) methods serve different
purposes and have distinct characteristics.
Static Methods
• Static methods belong to the class rather than any instance of the
class. They can be called without creating an instance of the class.
• Declared using the static keyword.
• Key Features of Static Methods:
 Belong to the class, not instances.
 Can be called using the class name.
 Cannot access instance variables/methods directly.
 Can access static variables/methods directly.
Example:
public class StaticExample {
// Static variable
static int staticVar = 10;
// Static method
static void staticMethod() {
System.out.println("Inside static method. Static Variable: " + staticVar);
}
public static void main(String[] args) {
// Call static method using class name
StaticExample.staticMethod();
}
}
Output:
Inside static method. Static Variable: 10
Non-Static (Instance) Methods
• Instance methods belong to instances of the class. They can
access instance variables and methods.
• Key Features of Instance Methods:
 Belong to instances of the class.
 Can be called on objects of the class.
 Can access instance variables/methods directly.
 Can also access static variables/methods.
 Does not use the static keyword.
Example:
public class InstanceExample {
// Instance variable
int instanceVar = 20;
// Instance method
void instanceMethod() {
System.out.println("Inside instance method. Instance Variable: " + instanceVar);
}
public static void main(String[] args) {
// Create an object of the class
InstanceExample obj = new InstanceExample();
// Call instance method using object
obj.instanceMethod();
}
}
Output:
Inside instance method. Instance Variable: 20
‫ لالطالع و المقارنة‬Example: Static Method vs.
public class MathUtils { Instance Method
// Static variable // Instance method
static double pi = 3.14159; public void displayDetails() {
// Static method for calculating the area System.out.println("Name: " + name + ", Age: "
+ age);
of a circle }
public static double // Static method (cannot access instance variables)
calculateCircleArea(double radius) { public static void showMessage() {
System.out.println("This is a static method in
return pi * radius * radius; Person class.");
} }
public static void main(String[] args) {
} // Calling static method directly using class
public class Person { name
MathUtils.calculateCircleArea(5);
// Instance variables
// Creating an instance of Person class
String name; Person person1 = new Person("Alice", 30);
int age; // Calling instance method using object
person1.displayDetails();
// Constructor to initialize instance // Calling static method directly using class
variables name
public Person(String name, int age) { Person.showMessage();
}
this.name = name; }
this.age = age;
Explanation: example

1.Static Method (MathUtils):


•calculateCircleArea(double radius) is a static method that
calculates the area of a circle using the formula pi * radius *
radius.
•It uses the static variable pi from the MathUtils class.
•It does not depend on any instance-specific data.
2.Instance Method (Person):
•displayDetails() is an instance method that prints the details
of a Person instance.
•It accesses instance variables name and age which are
specific to the particular Person instance.
3.Static Method (Person):
•showMessage() is a static method in the Person class that
prints a static message.
•It does not and cannot access instance variables name
and age.
Inner Classes
Definition of Inner Classes in Java
In Java, an inner class is a class that is defined within another
class. The enclosing class is referred to as the outer class.
There are several types of inner classes in Java:
1. Member Inner Class: Defined at the member level of a class
(same level as methods, constructors, or fields).
2. Static Nested Class: A static class defined at the member level
of an outer class.
Importance of Inner Classes
1. Encapsulation: Inner classes can access the private members of the outer class. This
capability allows them to implement encapsulated helper classes tightly coupled with the
outer class.
2. Code Readability and Maintainability: Inner classes can make code more readable and
maintainable by logically grouping relevant classes together, reducing the number of top-
level classes and simplifying the code structure.
3. Nesting for Namespace Management: Inner classes help to avoid name clashes with
other classes that might be defined elsewhere. This is particularly useful in large projects
where class names could collide.
4. Callbacks: Inner classes, especially anonymous inner classes, are often used to implement
event handlers or callbacks. They provide a simple way to handle events or implement
interfaces without creating a separate named class.
5. Improved Modularity: By grouping related classes together, inner classes enhance
modularity, making it easier to understand and manage the code.
1. Member Inner Class
• A member inner class is defined within the body of an outer class. It
can access all the members of the outer class, including private
members.
Example Explanation
Class Outer Declaration:
class Outer { ‫كالس الخارجي‬
private int outerVar = 10; This is the outer class that contains a private
member variable outerVar and an inner class
class Inner { ‫كالس الداخلي‬ Inner.
void display() { Private Variable outerVar:
System.out.println("outerVar = " + outerVar);
} private int outerVar = 10;
} This variable is a private member of the Outer
‫كائن في الكالس الخارجي‬ class and is initialized to 10.
public static void main(String[] args) { Member Inner Class Inner:
Outer outer = new Outer();
class Inner { ... }
Outer.Inner inner = outer.new Inner(); This is a non-static member inner class inside the
inner.display(); Outer class. It can access all members of the
} Outer class, including private members.
} ‫(كائن‬inner) ‫في‬ Method display in Inner Class:
Output: ‫الكالس الداخلي‬Inner
void display() { System.out.println("outerVar = " +
outerVar = 10
outerVar); }
This method prints the value of the outerVar
variable from the Outer class. Since Inner is a
member inner class, it can directly access
outerVar.
Explanation
Main Method in Outer Class:
public static void main(String[] args) { ... }
This is the entry point of the program.
Creating an Instance of Outer Class:
Outer outer = new Outer();
This line creates an instance of the Outer class.
Creating an Instance of Inner Class:
Outer.Inner inner = outer.new Inner();
This line creates an instance of the Inner class. Note that you need an instance
of the Outer class (outer) to create an instance of the Inner class because Inner
is a non-static inner class.
Calling the display Method:
inner.display();
This line calls the display method of the Inner class instance, which prints the
value of outerVar.
2. Static Nested Class

• A static nested class is a static member of the outer class. It


can only access the static members of the outer class.
Explanation
Example Class Outer Declaration:
class Outer {
private static int outerVar = 10; This is the outer class that contains a
private static member variable
static class Inner { outerVar and a static nested class
void display() { Inner.
System.out.println("outerVar = " + outerVar); Static Variable outerVar:
}
} private static int outerVar = 10;
This variable is a private static
public static void main(String[] args) { member of the Outer class and is
Outer.Inner inner = new Outer.Inner(); initialized to 10. Because it is static,
inner.display(); it belongs to the class Outer rather
} than to any instance of the class.
} Static Nested Class Inner:
Output:
static class Inner { ... }
outerVar = 10
This is a static nested class inside the
Outer class. It can access static
members of the Outer class,
including private static members.
Cont…
Method display in Static Nested Class:
void display() { System.out.println("outerVar = " + outerVar); }
This method prints the value of the static variable outerVar from the Outer
class. Since Inner is a static nested class, it can directly access the static
variable outerVar.
Main Method in Outer Class:
public static void main(String[] args) { ... }
This is the entry point of the program.
Creating an Instance of Static Nested Class Inner:
Outer.Inner inner = new Outer.Inner();
This line creates an instance of the static nested class Inner. Unlike non-
static member inner classes, a static nested class can be instantiated
without an instance of the outer class.
Calling the display Method:
inner.display();
This line calls the display method of the Inner class instance, which prints
the value of outerVar.

You might also like