0% found this document useful (0 votes)
7 views30 pages

Java Oop Lec5

The lecture notes cover advanced concepts in Java OOP, including classes, objects, constructors, member access modifiers, and garbage collection. Key topics include the declaration of variables, the use of static fields and methods, and the organization of classes into packages. The notes also explain member access levels (public, private, protected, package) and the importance of garbage collection in memory management.

Uploaded by

ly6110149
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)
7 views30 pages

Java Oop Lec5

The lecture notes cover advanced concepts in Java OOP, including classes, objects, constructors, member access modifiers, and garbage collection. Key topics include the declaration of variables, the use of static fields and methods, and the organization of classes into packages. The notes also explain member access levels (public, private, protected, package) and the importance of garbage collection in memory management.

Uploaded by

ly6110149
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

Java OOP

Class & Object 2


Lec5

Mohammed Sultan
1
Lecture Notes

1. More about class and object.


2. Constructors and Overloading
3. To understand logical class groupings using packages

4. Controlling Access to member of a class (Member Access


Modifiers)

5. Garbage Collector
• This is simplified version of a Student class, which could be
used to store information about students taking a course:
• class Student {
• String name; // Student's name.
• double test1, test2, test3; // Grades on three tests.
double getAverage() { // compute average test grade return
(test1 + test2 + test3) / 3;
• }
• } // end of class Student
Declaring a variable
• Student std;
• Declaring a variable does not create an object!
• In Java, no variable can ever hold an object.
A variable can only hold a reference to an object.
• Variables live in a heap(special portion of memory).
• A variable holds the information necessary to find the object in memory.
This information is called a reference or pointer to the object.
A null pointer exception error :
• This error occurred when the program attempts to use a null reference.

Ex.
std = null;
[Link]=“ ahmed”;
• Student std, std1, // Declare four variables of type Student
• std2, std3;
• std = new Student(); // Create a new object belonging to the // class
Student, and store a reference to that
• // object in the variable std
• std1 = new Student(); // Create a second Student object and
// store a reference to it in the variable
• std2 = std1; // Copy the reference value in std1 //
into the variable std2.
• std3 = null; // Store a null reference in the variable std3.
• [Link] = "John Smith"; // Set values of some instance variables. [Link] = "Mary
Jones";
• // (Other instance variables have default initial values of zero.)
Get and Set in java
• The get method returns the variable value, and the set method sets the
value.
• Syntax for both is that they start with either get or set , followed by the
name of the variable, with the first letter in upper case:

public class Person {


private String name;

Public setName(String newName){


[Link] = newName;
}

Public getName(){
Return [Link];
}
Static Fields
• The static keyword in java is used for memory management mainly.
• Keyword static before a field means the field is shared between all instances of the class.
• To call static method, use name of class, not individual object.

• The static can be:


1. Variable (also known as a class variable)
1. Static int x=5;
2. Method (also known as a class method)
3. Block
4. Nested class
X is static field that is shared
with all objects in memory

class Student{
int rollno;//instance variable
Obj1 String name;
Static int x; static String college ="ITS";//static variable
}

Obj2
Static Method
• If you apply static keyword with any method, it is known as static
method.
• A static method belongs to the class rather than the object of a class.
• A static method can be invoked without the need for creating an
instance of a class.
• A static method can access static data member and can change the
value of it. class Student{
int id;
String name;
static String college = "ITS"; //static method to change the value of static variable

static void change(){


college = “SE";
}
Restrictions for the static method
• There are two main restrictions for the static method. They are:
1. The static method can not use non static data member or call non-static
method directly.
2. this and super cannot be used in static context.

Output:Compile Time Error


Java static block
• Is used to initialize the static data member.
• It is executed before the main method at the time of classloading.

Output:
static block is invoked
Hello main
Putting classes in packages
To put a class into a package, one uses the "package" statement
The package statement MUST be the first line of code within the file.
It can be proceeded by comments.

If no package statement is supplied, the class is placed in the "default" package


The default package is a package with no name

package javaApps;

public class Std


{
[...]
Importing Classes

• There are two ways for importing classes:


• 1- import one class
• Import [Link];

• 2- import all classes in the package


• Import [Link].*;
Notes on the import statement
Import ONLY imports public classes from the specified package
Classes which are not public cannot be referenced from outside their package.

There is no way to "import all classes except one"


import either imports a single class or all classes within the package
Note: importing has no runtime or performance implications. It is only importing a namespace
so that the compiler can resolve class names.

Import statements must appear at the top of the file after the package statement
and before any class or interface definitions.
Member Access Modifiers

• Java supported four type of member access modifier :


[Link]

2. private

3. protected

4. package
The following chart shows the access level
permitted by each specifier.

Specifier class subclass package world

private X

protected X X* X

public X X X X
package X X
Public

• Any class, in any package, has access to a class's public members.

• Declare public members only if such access cannot produce


undesirable results if an outsider uses them .
package Greek;
public class Alpha {
public int iampublic;
public void publicMethod() {
[Link]("publicMethod");
import Greek.*;
} class Beta {
} void accessMethod() {
Alpha a = new Alpha();
[Link] = 10; // legal
[Link](); // legal
}
}
As you can see from the above code, Beta can
legally inspect and modify the iampublic variable
in the Alpha class and can legally invoke
publicMethod.
Private

• A class member that is declared private may only be accessed by


method within the same class as the class member

• A private member is accessible only to the class in which it is defined .

• Private members are like secrets you never tell anybody.

• To declare a private member, use the private keyword in its declaration


Private
class Alpha {
private int iamprivate;
private void privateMethod()
{
[Link]("privateMethod");
}
}
class Beta {
void accessMethod() {
Alpha a = new Alpha();
[Link] = 10; // illegal
[Link](); // illegal
}
}
❖The Beta class cannot access the iamprivate
variable or invoke privateMethod on an object of
type Alpha because Beta is not of type Alpha.
Compiler error
When one of your classes is attempting to access a
member variable to which it does not have access, the
compiler prints an error message similar to the
following and refuses to compile your program:
[Link]: Variable iamprivate in class Alpha not
accessible from class Beta.
[Link] = 10; // illegal
^1 error
Protected
• Members can be accessed by method in all classess within the same
package as the class in which the member is defined.
• Which allow the class itself, subclasses, and all classes in the same
package to access the members.
• Protected members are like family secrets--you don't mind if the
whole family knows, and even a few trusted friends but you wouldn't
want any outsiders to know.
package Greek;
Public class Alpha {
protected int iamprotected;
protected void protectedMethod() {
[Link]("protectedMethod");
}
}
package Greek;
class Gamma {
void accessMethod() {
Alpha a = new Alpha();
[Link] = 10; // legal
[Link](); // legal
}
}
Package
• The package access level is what you get if you don't
explicitly set a member's access to one of the other levels.
// class to test package access
Public class testp{
// define the main method Class Accesst
Public statc void main(string[] args){ {
// instantiate a accesst object Int x=1;
Accesst a=new Accesst(); String s=“before”;
[Link]([Link]() ); //method tostring()
a.x=3; Public string tostring() {
a.s=“after”; return(s + x); }
[Link]([Link]() ); }
} Execution :
} before 1
after 3
Garbage Collection

•Returns memory to system


•Java performs this automatically
•Object marked for garbage collection if
no references to it
Ex:
Student std = new Student("John Smith");
std = null;
• A programmer might accidentally delete an object
even though there are still references to that object.
This is called a dangling pointer error, and it leads to
problems when the program tries to access an object
that is no longer there .
Java uses a procedure called garbage
collection to reclaim memory occupied by
objects that are no longer accessible to a
program
Any Questions?

You might also like