Chapter3-Class & Objects
Chapter3-Class & Objects
1
3.1. Introduction
Classes
A set of similar objects is called a class.
Model objects that have attributes (data members) and behaviors
(member functions)
Defined using keyword class
Have a body delineated with braces ({ and })
Example: public Student{….}
Each .java source file may contain only one public class. A source file may
contain any number of default visible classes.
Finally, the source file name must match the public class name and it must
have a .java suffix.
Object
An Object represents a real world entity. It is complete and self
contained with distinct characteristics and behaviors.
Is a unique instance of one class
Eg: Student s1=new Student (“Abebe”,20)
2
S1:-is an object
Cont…
Eg:
class Student. { String name; int rollno; int age; }
Student std=new Student();
The new operator dynamically allocates memory for an object
3
Cont…
Methods
Method describe behavior of an object.
A method is a collection of statements that are group together to perform
an operation.
Syntax :
return-type methodName(parameter-list) { //body of method }
Example
public String getName(String st)
{ String name="StudyTonight";
name=name+st; return name; }
Member Methods
Methods that are defined in the class and invoked using the class object
Eg: public int getAge():-is a member function
Static methods:
Methods that can be defined by using keyword static and can be called
using simple function name or clasname.functionname
Eg: public static void disp();….
its function calling will be :disp()/clasname.disp()
4
Cont…
Constructor
A class contains constructors that are invoked to create
objects from the class blueprint.
Constructor declarations look like method declarations—
except that they use the name of the class and have no return
type.
For example, Student constructor:
private String name; private int age;
public Student(String n, int a) {
name=n;
age=a;
}
To create a new Student object called s1, a constructor is
called by the new operator:
Student s1=new Student (“Abebe”,20);//creates space in memory for the
object and initializes its fields.
5
Cont…
We can also create a no-argument constructor/default-const:
public Student() {name=”abebe”; age=12;}
Difference b/n Constructors & Methods???
constructors can not return a value and are only called once (return
current instant of a class)
while regular methods could be called many times and it can return a
value or can be void.
Static variable
Memory for static variable is created only one in the program at
the time of loading of class.
These variables are preceded by static keyword. static variable
can access with class reference.
static variable not only can be access with class reference but
also some time it can be accessed with object reference.
Non-static variable
Memory for non-static variable is created at the time of create an
object of class.
These variable should not be preceded by any static keyword
Example: These variables can access with object reference.
7
Cont…
Static-variable
Non-static variable
preceded by static keyword.
No static keyword-EG:
class A
class A
{
{
static int b;
int a;
}
}
They are common for every
They are specific to an
object /there memory location
object
can be sharable by every
They can access with object reference or same
object reference. class.
Syntax Static variable can access with
obj_ref.variable_name class reference.
Syntax:class_name.variable_nam
8
cnt’d…
Non-static variable Static-variable
Memory is allocated for Memory is allocated for
these variable whenever an these variable at the time of
object is created loading of the class.
9
Example-1 Student s2=new Student();
class Student s2.roll_no=200;
{ int roll_no; s2.marks=75.8f;
float marks; s2.name="zyx";
String name;
System.out.println(s2.roll_no);
static String College_Name="ITM"; }
System.out.println(s2.marks);
class StaticDemo { System.out.println(s2.name);
public static void main(String args[])
{ System.out.println(Student.Colle
Student s1=new Student();
ge_Name);
s1.roll_no=100; }
s1.marks=65.8f;
}
s1.name="abcd";
System.out.println(s1.roll_no); What will be the output?
System.out.println(s1.marks);
System.out.println(s1.name);
System.out.println(Student.College_Nam
e); 10
Pictorially:
11
Example-2 (predict output for both???)
class Counter
{
int count=0;// what if it is static int count=0;
Counter()
{
count++;
System.out.println(count);
}
public static void main(String args[])
{
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
}
}
12
3.3 Access Specifiers
The four access levels are −
Visible to the package, the default. No modifiers are needed.
Visible to the class only (private).
Visible to the world (public).
Visible to the package and all subclasses (protected).
Note:
a class cannot be associated with the access modifier private, but
if we have the class as a member of other class, then the inner
class can be made private.
outer classes can only be declared public or package private.
Use the most restrictive access level that makes sense for a
particular member. (private )unless you have a good reason not to.
Avoid public fields except for constants.It is not recommended for
production code. (Public fields tend to link you to a particular
implementation)
13
Cont… 2. Private Access Modifier
1. Default Access Modifier - Methods, variables, and
No Keyword constructors that are
declared private can only be
we do not explicitly declare an
accessed within the declared
access modifier for a class, field,
class itself.
method, etc.
the most restrictive access
A variable or method declared
level. Class and interfaces
without any access control
cannot be private.
modifier is available to any other
class in the same package. Using the private modifier is
the main way that an object
Example: encapsulates itself and
Variables and methods can be hides data from the outside
declared without any modifiers, − world.
String version = "1.5.1"; Example:
boolean processOrder() { public class Eg1 {
return true;}
private String name;
public String getName() {
return this.name; } 14
Cont… 4. Protected Access Modifier
Variables, methods, and
3. Public Access Modifier
constructors, which are
A class, method, constructor, declared protected in a
interface, etc. declared public can superclass can be accessed
be accessed from any other class. only by the subclasses in
Therefore, fields, methods, blocks other package or any class
declared inside a public class can within the package of the
be accessed from any class protected members' class.
belonging to the Java Universe. The protected access
However, if the public class we are modifier cannot be applied
trying to access is in a different to class and interfaces.
package, then the public class still Methods, fields can be
needs to be imported. Because declared protected, however
of class inheritance, all public methods and fields in an
methods and variables of a class interface cannot be declared
are inherited by its subclasses. protected.
Example
public static void main(String[]
arguments) { // ...} 15
Cont…
Protected access gives the subclass a chance to use the helper
method or variable, while preventing a nonrelated class from trying to
use it.
Example
its child class override openSpeaker() method −
class AudioPlayer {
protected boolean openSpeaker(Speaker sp) { //
implementation details }}
class StreamingAudioPlayer
{//sub-class
boolean openSpeaker(Speaker sp)
{ // implementation details }}
What if it (openSpeaker) is declared as private? Or public?
16
how access levels affect visibility
Summary
in class relationships
17
Example-1(class & Objects)
public class simpleClass {
private String name;
private int age;
public simpleClass(String n,int a)
{
this.name=n; //what if there is setter methods?
this.age=a;
}
public String getName()
{ return name; }
public int getAge()
{ return age; }
public static void main(String args[])
{ simpleClass s1=new simpleClass("abe",12);
String n=s1.getName();
int a=s1.getAge();
System.out.println(n+"\t"+a);
} 18
Example-2(static-methods)
import java.util.Scanner;
public class Func1 {
public static void main(String[] args)
{ pr();
Func1.pr2();
}
public static void pr()
{ System.out.println("hello");}
20
3.4 This and this()
this keyword
is used to refer always current object/current instance of a class,
this is a non static and can not be used in static context, which means you
can not use this keyword inside main method in Java(compilation error)
this() method
is used to access one constructor from another where both constructors
belong to the same class
With the both, inheritance is not involved; everything happens within
the same class.
OR it can be used in constructor chaining to call another constructor
e.g. this() calls no argument constructor of child and parent class.
Note:
Another use of this in Java is for accessing instance variables of a class
and it's parent (if it is the same instance-to remove ambiguity)
You can not reassign the (this variable) because you can not assign a
new value to final variable this".-they are special variables and they are
final
21
Examples-predict?
Eg-2
Eg-1
public class Officer
public class Number
{ public Officer() {
{ int num;
public void favorite(int num) this(“Second");
{ this.num = num; System.out.println(“I am First");
} }
public static void main(String args[]) public Officer(String name) {
{ System.out.println("Officer name is "
Number n1 = new Number(); + name); }
n1.favorite(8); public Officer(int salary) {
System.out.println("Your favorite this();
number is " + n1.num);
System.out.println("Officer salary is
}
Rs." + salary); }
}
public static void main(String args[])
What if num=num? { Officer o1 = new Officer(9000);
22
Cont…
The this is also used to call Method of that class.
public void getName()
{
System.out.println("Studytonight"); }
public void display()
{
this.getName();
System.out.println(); }
this is used to return current Object
public Car getCar()
{ return this; }
23
3.5 Mutable & Immutable Class
Mutable classes
We can change the state of object after initiation in case of
mutable classes.
These classes are not thread safe so we should use proper
synchronize block to access its member data(instance
variable).
Its recommended to create getter and setter methods in
muttable class to embrace Encapsulation.
With mutable objects you can change the state anytime during its
lifetime (via the setters),
whereas with immutable objects you change only set its state when
you create it (via the constructor).
24
Cont…
Immutable Classes
are those classes whose state can not be changed after
initiation(object creation).
Immutable classes have only one state for whole life; So we
can use these classes in multi-threading code without any data
inconstancy.
because the effect of state change is often dependent on the
order of a sequence of events, which you can't guarantee during
multithreaded operation.
Immutable classes do not required setter methods :
Immutable classes are final no one can extend them(if you
need to extend one class not make/call this immutable)
Java itself provide many immutable classes - String, Integer,
Boolean, Float, other Wrapper classes.
For the JVM, there is no notion of "mutable" or "immutable" classes, and
mutable objects are not treated differently from immutable objects.
25
Examples:
class Mutable{
private int value;
Eg-2
public Mutable(int value) { class Person {
public int age;}.
this.value = value;
The age variable can be
} changed, hence mutability
getter and setter for value achieved. whereas
} class Person {
public final int fingerNo = 10;}.
class Immutable { Immutable objects can't be
changed:
private final int value;
public Immutable(int value) {
this.value = value; }
only getter
26
}
3.6 Packages
• Packages in Java are a way of grouping similar types of
classes / interfaces together.(acts as a container for group
of related classes).
• It is a great way to achieve reusability.
• We can simply import a class providing the required
functionality from an existing package and use it in our
program.
• it avoids name conflicts and controls access of class, interface and
enumeration etc
• It is easier to locate the related classes
• The concept of package can be considered as means to achieve data
encapsulation.
• consists of a lot of classes but only few needs to be exposed as most
of them are required internally. Thus, we can hide the classes and
prevent programs or other packages from accessing classes which
are meant for internal usage only. 27
Cont…
The Packages are categorized as :
29
Cont..
Subpackage
A package created inside another package is known as
a subpackage.
When we import a package, subpackages are not imported by
default. They have to be imported explicitly.
Eg:
import java.util.*;(util is a subpackage inside java package)
import javax.swing.Jbutton;?
import java.io.*;?
import javax.swing.ActionListener;?
30
Import and Static Import
Import :
It facilitates accessing any static member of an imported class
using the class name.
import java.lang.Math;
public class Eg1 {
public static void main(String args[]) {
double val = 64.0;
double sqroot = Math.sqrt(val);
System.out.println("Sq. root of " + val + " is " + sqroot
);
}
}
31
Cont…
Static Import
It facilitates accessing any static member of an imported class
directly i.e without using the class name.
import static java.lang.Math.*;
public class Eg2 {
public static void main(String args[]) {
double val = 64.0;
double sqroot = sqrt(val);
System.out.println("Sq. root of " + val + " is "
+ sqroot);
}
}
32
User defined packages
Creating a package in java is quite easy.
Simply include a package command followed by
name of the package as the first statement in java
source file.
package RelationEg;
33
package REL1;
public class Comp1 {
public int getMax(int x, int y) {
if ( x > y ) {
return x;
}
else {
return y;
}
}
}
34
package packageeg;
import REL1.Comp1;
public class EgComp {
public static void main(String args[]) {
int val1 = 7, val2 = 9;
Comp1 comp = new Comp1();
int max = comp.getMax(val1, val2); // get the max value
System.out.println("Maximum value is " + max);
}
}
35