Object Oriented Programming

Topics:-
• OO Principles
• Object characteristics
• Defining Objects
• Constructors
• Overloading

Object of Multiple objects
• One object? or multiple objects? 


Objects of Class
• Define the Class
• Create instance of the Class (Instantiate
Object)
• Using different parts of an Object 

Defining a Class
Format:
public class <name of class>
{

instance variables (Information)
instance methods (Capabilities)
}

Example:
public class Person
{
// Define instance variables
// Define instance methods

Format of instance variables/attributes:
<access modifier>1 <type of the field> <name of the field>;
Example
public class Person
{
private int age;

• Format of instance methods:
<access modifier>1 <return type2> <method name> (<p1 type> <p1 name>…)
{
<Body of the method>
}
Example of an instance method:
public class Person
{
public void fun (int num)
{
System.out.println (num);
}

Complete definition
public class Person
{
private int age;
public void setAge (int anAge)
{
age = anAge;
}
public int getAge ()
{
return age;
}

Declaring Vs. Instantiating Object
• Declaring a reference to a ‘Person’
Person ramlal;
• Instantiating of a ‘Person’
ramlal = new Person (); 

Using parts of an Object
Format:
<instance name>.<attribute name>;
<instance name>.<method name>(<p1 name>, <p2
name>…);
Example:
int anAge = 27;
Person ramlal = new Person ();
ramlal.setAge(anAge);
System.out.println(ramlal.getAge());
 

Driver
• Your program should contain a DRIVER class
• This is where the program starts running
– Contains the MAIN method
• Instances of other Classes can be created here
• Keep all the classes of a particular program in the same directory 
• Codes for each class should be kept in
different java files

Person.java
class Person
{
: :
}        
             


 Driver.java 
class Driver
{
: :

Putting it altogether
public class Driver
{
public static void main (String [] args)
{
int anAge = 27;
Person ramlal = new Person ();
ramlal.setAge(anAge);
System.out.println(“Ramlal's current age is..." +
ramlal.getAge());
}

public class Person
{
private int age;
public void setAge (int anAge)
{
age = anAge;
}
public int getAge ()
{
return age;
}

Compiling with Multiple Classes
• In the previous example there were two classes:
‘Driver’ and ‘Person’.
• One way (safest) to compile the program is to
compile each source code (dot-Java) file:
javac Driver.java
– javac Person.java

• However in this program a method of the Driver
class refers to an instance of class Person.
public static void main (String [] args)
{
Person ramlal = new Person ();
}
• The Java compiler can detect that this dependency
exists. 
• Effect:: when the Driver class is compiled, the
code in class Person may also be compiled
– Typing: “javac Driver.java” produces a
“Driver.class” file (or produces an updated
compiled version if a byte code file already exists).
– If there is no “Person.class” file then one will be
created.
– If a “Person.class” file already exists then an updated
version will not be created (unless you explicitly
compile the corresponding source code file) 
MORAL :: when making changes to multiple
source code
– make sure that you compile each individual file
or
– at least remove existing byte code (dot-class) files
prior to compilation

 UML
• Unified Modeling Language
• Graphical language
– Visualizing
– Specifying
– Constructing
– Documenting


Class Diagram
• Describes the structure of a system
• Shows the system's
 classes
Attributes
operations (or methods), 
Relationships among the classes.
Elements of Class Diagrams
• Class
• Attributes
• Operations
• Relationships
    – Associations
    – Generalization
    – Realization
    – Dependency
• Constraint Rules and Notes 


Classes
• Describes a set of objects having similar:
– Attributes (status)
– Operations (behavior)
– Relationships with other classes
• Attributes and operations may
– have their visibility marked:
– "+" for public
– "#" for protected
– "−" for private
– "~" for package


Class Name
 Window

Attributes
size: int
visibility: boolean

Operations-
display()
 hide()

UML of a Class
<Name of class>
-<attribute name>: <attribute type>
+<method name> ()


Example:-
Foo
-num: int
+getName (): String
+setName (String): Void

Why UML
• Images are better than text for showing
structural relations
 Text
Jane is Jim’s boss.
Jim is Joe’s boss.
Anne works for Jane.
Mark works for Jim
Anne is Mary’s boss.
Anne is Mike’s boss.



Referring Methods from Inside or
Outside

public class Foo
{
private int num;
public Foo () { num = 0; }
public void methodOne () { methodTwo()
/*
Call is inside the
scope (no
instance name or
‘dot’ needed*/
; }
public void methodTwo () { System.out.println(num); }
: : :
}
public class Driver
{
main ()
{
Foo f1 = new Foo ();
Foo f2 = new Foo ();
f1.methodOne()
/*
Call is outside the
scope (instance
name and ‘dot’ IS
needed*
/
;
}
}


Shadowing
public class Foo
{
// Attributes-Second: Look for an attribute
by that name
private int num;

public void method ()
{
// Local variables-First: Look for a local
identifier by that name
int num;

num = 1;
}
}


Properties of OOP
Encapsulation
– Hiding data by restricting ACCESS
Abstraction
– Hide details, show Features
Polymorphism
– One name, Many Forms
Inheritance
– How objects relate to each-other
Encapsulation
• Protect the inner-workings (data) of a class.
• Only allow access to the core of an object in a
controlled fashion
– (use the public parts to access the private sections). 
Overloading
• Methods that implement SIMILAR but NOT
IDENTICAL tasks
• Regarded as good programming style
Things to avoid
– Distinguishing on the ORDER of the Parameters
– Overloading methods with identical
Implementation 
Method Signature
• Unless there is a compelling reason do not change the
signature of your methods!

class Foo
{
void fun ()
{
}
}
Before:
class Foo
{
void fun (int num)
{
}
}
After:
public static void main ()
{
Foo f = new Foo ();
f.fun () //
This change has broken me!  
}

HAS-A Relation
• objects of one class can call the methods of
another class.
• Typically this type of relationship exists
between classes when a class is an attribute of
another class.

public class Car
{
private Engine anEngine;
private Lights headLights;
public start ()
{
anEngine.ignite ();
headLights.turnOn ();
}
}
 
public class Engine
{
public boolean ignite () { .. }
}
public class Lights
{
private boolean isOn;
public void turnOn () { isOn =
true;}
}


Directed Association
Unidirectional
– The association only goes in one direction.
– You can only navigate from one class to the other
(but not the other way around).
– e.g., You can go from an instance of Car to Lights
but not from Lights to Car, or you can go from an
instance of Car to Engine but not from Engine to
Car.
• Bidirectional
– The association goes in both directions
– You can navigate from either class to the other
– e.g.

public class Student
{
private Lecture [] lectureList = new Lecture [5];
:
}
public class Lecture
{
private Student [] classList = new Student [250];
:


Automatic Garbage Collection
• Dynamically allocated memory is automatically freed
up when it is no longer referenced.
• Dynamically allocated memory is automatically freed
up when it is no longer referenced
• e.g., f2 = null;


Finalize()
• Example sequence:

public class Foo
{
int num;
public Foo () { num = 1; }
public Foo (int newValue) { num = newValue; }
: : :
}
: :
Foo f1 = new Foo ();
public class Foo
{
int num;
public Foo () { num = 1; }
public Foo (int newValue) { num = newValue; }
: : :
}
: :
Foo f1 = new Foo ();
f1 = new Foo (10);
public class Foo
{
int num;
public Foo () { num = 1; }
public Foo (int newValue) { num = newValue; }
: : :
}
: :
Foo f1 = new Foo ();
f1 = new Foo (10);


• The Java interpreter tracks what memory has been
dynamically allocated.
• It also tracks when memory is no longer referenced.
• When the system isn’t busy, the Automatic Garbage
Collector is invoked.
• If an object has a finalize method then it is invoked:
– The finalize is a method written by the programmer to free
up non-memory resources e.g., closing and deleting
temporary files created by the program, closing network
connections.
– This method takes no arguments and returns no values
(i.e., returns void)
– Dynamic memory is NOT freed up by this method.
• After the finalize method finishes execution,
the dynamic memory is freed up by the
Automatic Garbage Collector.

void finalize() {

}


Constructors
• Sometimes, it is tedious to initialize all
attributes manually
• Better if can be done at the time of creation
• Solution: use of Constructors
– Automatically called after object creation
– Before “new” finishes its job.
– Same name of the class 

Format:
<access> <NameOfClass>(param_list) {
//initialization code }

• Access is : private, protected, public, package
(default)

 • Example:
class Dog {
String name;
String breed;
// like default constructor
public Dog() {
}
}
… Dog myDog = new Dog();

• Name, breed cannot be NULL, Hence we can init like
class Dog {String name;
String breed;
public Dog() {
name = "unknown";
breed = "unknown";
}
}

Dog myDog = new Dog();

• If Name and Breed are known
class Dog {String name;
String breed;
public Dog(String n, String b) {
name = n;
breed = b;
}
}
….
Dog myDog = new Dog(“George”, “Poodle”);


Overloading constructor
Situations where we know the Name, but not
the Breed?

public Dog(String n) {
name = n;
breed = “unknown”;
}

• But, both the situations may be present at
different instantiations
– We know the Name only
– We have both the information
• How do we handle such situations?

class Dog {
String name;
String breed;
public Dog(String n) {
name = n;
breed = “unknown”;
}
public Dog(String n, String b) {
name = n;
breed = b;
}
}


class Dog {
String name;
String breed;
public Dog() {
name = "unknown";
breed = "unknown";
}
public Dog(String n) {
name = n;
breed = “unknown”;
}
public Dog(String n, String b) {
name = n;
breed = b;
}
}


Driver Method
class Driver {
public static void main(String [] args){
Dog myDog1 = new Dog();
}

class Driver {

public static void main(String [] args){
Dog myDog1 = new Dog();
Dog myDog2 = new Dog(“George”);
}

class Driver {

public static void main(String [] args){
Dog myDog1 = new Dog();
Dog myDog2 = new Dog(“George”);
Dog myDog3 = new Dog(“George”, “Poodle”);
}



This()
• It’s an invocation to the constructor of a class.
• It can be used when constructors have been
overloaded.

public class Foo
{
private int num1;
private int num2;
public Foo ()
{
num1 = 0;
num2 = 0;
}
public Foo (int n1)
{
this ();
num1 = n1;
}
}


Example: this()
public class Dog {
private String name;
private String breed;
Dog(){
name = "UK";
breed = "UK";
}
Dog(String n){
this();
name = n;
}
Dog(String n, String b){
this(n);
breed = b;
}


public void Disp(){
System.out.println("\nName: " + name + "\tBreed: " + breed);
}
}
class Driver {
public static void main(String [] args){
Dog d1 = new Dog("George");
Dog d2 = new Dog("Jenny", "BullDog");
d1.Disp();
d2.Disp();
}
}

Copyright © C Program | Java | OpenGL Programming | Hadoop at Computaholics