chapter-two (classes and objects)
chapter-two (classes and objects)
Undergraduate Program
Course Code: SE132
Course Title: Object Oriented
Programming
Classes & Objects
Class Declaration & Object
Instantiation
A class is a blueprint from which an object is created (instantiated)
A class is a means to create user defined data type
A class represents the set of properties & methods that are common to all objects
of the same type. e.g. Car, Person, Student
Class declaration has the following syntax
[access modifiers] class NameOfClass {
...
}
Example
public class Rectangle{
...
}
Methods and Their Components
A Java method is a collection of statements that are
grouped together to perform an operation.
//constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
Cont...
The this key word is also used to call constructors within the same class
E.g. public class Rectangle {
private int x, y;
private int width, height;
public Rectangle() {
this(0, 0, 1, 1);
}
public Rectangle(int width, int height) {
this(0, 0, width, height);
}
public Rectangle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
}
Access Modifiers
As the name suggests access modifiers in Java helps to restrict the scope
of a class, constructor, variable, method, or data member.
There are four access modifiers
• Default – if no explicit access modifier assigned to a class, method or
data member, the default access modifier is used
– A class, method or property with default access modifier is
accessible within the package it is defined
• Private – it is used to enforce data hiding principle of the object
oriented paradigm
– A property or method declared with private visibility is not
accessible outside of a class
– It is not applicable to class
– It requires setters and getters to set or read its values
Cont…
• Protected - the methods or data members declared as
protected are accessible within the same
package or sub-classes in different packages.
– It is not applied to class
• Public - the public access modifier has the widest scope among
all other access modifiers
– Classes, methods, or data members that are declared as
public are accessible from everywhere in the program.
There is no restriction on the scope of public data members.
Instance and Static Members
Instance Members
– Objects created from a class will have its own copy of
the properties defined in the class. The properties of an
object are called instance variables
// four constructors
public Rectangle() {
origin = new Point(0, 0);
}
public Rectangle(Point p) {
origin = p;
}
public Rectangle(int w, int h) {
origin = new Point(0, 0);
width = w;
height = h;
}
Cont...
public Rectangle(Point p, int w, int h) {
origin = p;
width = w;
height = h;
}