Object-Oriented Programming Concepts


The Object-Oriented (OO) approach focuses on modeling and defining systems by organizing them into objects which express well-defined missions and responsibilities.

Java – Download Free EBooks and Whitepapers

Object-Oriented =Objects + Classes + Inheritance + Communication with messages

Java™ Application Development on Linux® – Free 599 Page eBook

Enterprise Java Virtualization:

Understanding the TCO Implications

InfoWorld’s Java IDE Comparison Strategy Guide:

Java Essential Training

Apache Jakarta Commons: Reusable Java™ Components

Enabling Rapid ROI: With Java™ – Based Business Intelligence Applications:

Classes

A class is a named collection of fields that hold data values and methods that operate on those values.

A class is a template or type that describes the field and methods that are grouped together to represent something.

A class is a non-primitive (user-defined) data type.

Instance variables + methods = members

class Point

{

private double x, y;

public Point(double first, double second)

{

x = first;

y = second;

}

public double distanceFromOrigin()

{

return Math.sqrt(x * x + y * y);

}

}

public class MyClass

{

public static void main(String[] args)

{

Point p = new Point(10, 10);

System.out.println(p.distanceFromOrigin());

}

}

Class fields

Also called per-class field

E.g.

private static int count;

public static final double PI=3.14159;

public static int SIMPLE=0,ONE_SPRING=1,TWO_SPRING=2;

Only a single copy of a static field exists. This field is associated with class itself and not with instances of a class.

Class methods  

Belongs to class a whole rather than an instance i.e. they are associated with class rather than object.

class Employee

{

static int total_employees;

static void clear()

{

total_employees = 0;

}

static int getTotalEmployees()

{

return total_employees;

}

}

In call: Employee.clear();

Instance fields 

Every object has own copy of instance fields.

Access

Inside class:          name

Outside class:       objectname.fieldname

Example

class Circle{

double r;

}

Circle c = new Circle();

c.r=2.0;

Circle d = new Circle();

d.r=c.r*2;

Instance Methods

Operates on an instance of a class

Example

Circle c = new Circle();

c.r=2.0;

double a=c.area();

Can access class fields/methods

Object 

Object is a real or abstract thing that has state, behaviour and identity.

a)      State: The information (data) an object maintains.

  • Data encapsulated by the object
  • Data stored as attributes
  • Customer address: changes even though customer does not
  • Some are immutable: customer id number

b)      Behaviour: the operations an object can perform

  • Object acts on messages (function calls)
  • Outside world interacts through messages: code generally doesn’t change the state directly
  • Have well-defined interface

c)      Identity: is the property of an object that distinguishes it from all other objects.

  • In programming, object normally referred to by a name, but the only really consistency identity is the address at which it is stored.

An object is an instance of a class.

public class Circle

{

private static int count;// data

private static final double PI = 3.1459;// data

// class method

public static double radToDeg(double rads)

{

return rads * 180 / PI;

}

private double r;// data

// constructor

public Circle(double radius)

{

r = radius;

}

// instance method

public double area()

{

return PI * r * r;

}

// instance method

public double circum()

{

return 2 * PI * r;

}

// class method

public static double area(double r)

{

return PI * r * r;

}

public static void main(String[] args)

{

double radius = 10;

Circle c = new Circle(radius);// instance created

System.out.println(c.area());

System.out.println(Circle.area(radius));

}

}

Constructor

A constructor is method defining declarations and instantiation of class of objects.

Example

Circle c = new Circle();

Every class in Java has at least one constructor whose name is same as the class name and whose purpose is to perform any necessary initialization for new object.

Default constructor: constructor with no arguments. No special initialization. If not defined any constructor, compiler generates a default constructor.

Defining a constructor

public class Circle{

public double r;

//default costructor

public Circle()

{

// TODO Auto-generated constructor stub

}

public static void main(String[] args)

{

Circle c= new Circle();

}

}

Refer to Constructors for detail information.

Encalsulation  

The wrapping up of data & methods into single unit is known as encapsulation.

The data is not accessible outside the methods wrapped in the class. Data is private & public methods become interface between object’s data & program.

Providing access to an object only through its messages, while keeping the details private is called information hiding.

There are degrees of information hiding, ranging from partially restricted visibility to total invisibility.

E.g.

class A {

int x;

public:       void set_x(int i) {x = i;}

int get_x() {return x;}

}

Data Abstraction  

Abstraction refers to the act of representing essential features without including the background details.

Suppose that we are doing graphics of some sort, and are concerned with X,Y points on a screen. Now, at a low enough level, a point might be described via a couple of floating-point numbers X and Y. But with data abstraction, we define a type “Point” that will refer to a point, and we hide from the users of the type just how such a point is implemented. Instead of directly using X,Y values, we present Point as a distinct data type, along with some operations on it.

Inheritance  

The sharing of features among classes related by generalization.

It refers to the sharing of attributes and operations among classes based on a hierarchical relationship. A class can be refined into subclasses and each subclass inherits all the properties of its subclass and adds its own unique properties.

Inheritance is the process by which one object can acquire the properties of one or more objects. More specifically, an object can inherit a general set of properties to which it can add those features that are specific only to it.

Example

class Person

{

private String name;

public void setName(String n)

{

name = n;

}

public String getName()

{

return name;

}

}

class Student extends Person

{

private String stuNum;

public void setStuNum(String sn)

{

stuNum = sn;

}

public String getStuNum()

{

return stuNum;

}

}

Shadowing superclass fields

public class A

{

int x;

}

public class B extends A

{

int x;

}

public class C extends B

{

int x;

}

          In methods of class C            Class referenced

x                                              C

this.x                                        C

super.x                                     B

((B)this).x                                B

((A)this).x                                A

super.super.x                           Not allowed

Method overriding

When a class defines an instance method using the same name, return type, and parameters as a method in its superclass that method overrides the method of the superclass.

  • Overriding is only for instance methods.
  • Class methods can be shadowed by a subclass but not overridden i.e. static methods do not participate in overriding. Overriding is not shadowing
  • Class methods cannot hide/shadow instance methods

static void g(){                       void g(){

}                                              }

  • Methods cannot be overridden to be more private; only to be more public.
  • Any exceptions declared in overriding method must be of the same type as those thrown by the super class, or a subclass of that type.
  • Final methods and private methods cannot be overridden.
Overloading Overriding
 Same name but different arguments. Same return type, name, arguments
Return type does not count Return type counts
Access modifiers also remain same. Access modifiers cannot be more restrictive.
No requirement relating to exceptions. It cannot throw more checked exceptions.
No inheritance, same class Inheritance
Compile-time Run-time (Dynamic binding)

Example 

class A{                                                      class B extends A{

int i=1;                                                       int i=2;

int f(){                                                        int f(){

return i;                                                     return -i;

}                                                                 }

static char g(){                                          static char g(){

return ‘A’;                                                   return ‘B’;

}                                                                 }

}                                                                 }

public class Test

{

public static void main(String[] args)

{

B b = new B();

System.out.println(b.i); // 2

System.out.println(b.f()); // -2

System.out.println(b.g()); // B

System.out.println(B.g()); // B

A a = (A) b;

System.out.println(a.i); // 1

System.out.println(a.f()); // -2

System.out.println(a.g()); // A

System.out.println(A.g()); // A

}

}

Abstract classes  

Superclass that declares the structure of a given abstraction without providing a complete implementation of every method is called an abstract class

  • Any class that contains one or more abstract methods must also be declared abstract.
  • Any subclass of an abstract class must either implement all of the abstract methods in the superclass or be itself abstract i.e subclass should override each of the abstract methods of its superclass and provide an implementation for all of them.
  • There can be no object of abstract class i.e. abstract class cannot be instantiated.
  • Cannot declare abstract constructors. Static, private, final methods cannot be abstract.

Example

abstract class A

{

abstract void call(); // abstract void call(){};

void call2()

{ // is CTE

System.out.println(“In call2”);

}

}

class B extends A

{

void call()

{

System.out.println(“In B”);

}

}

public class AbstractDemo

{

public static void main(String[] args)

{

B b = new B();

b.call();

}

}

Java source file (general form)

  • A single package statement                        (optional)
  • Any number of import statements                 (optional)
  • A single public class declaration                   (required)
  • Any number of package private classes         (optional)

Each file can contain at most one class that is declared public. A public class is one that is designed for use by other classes and packages.

The restriction on public classes only applies to top-level classes; a class can contain any number of nested or inner classes that are declared public.

Access protection/control

  • Modifiers specify the access rules for field/methods
  • Many levels of protection to allow fine-grained control over how visible variables and methods are.
  • Classes and packages are two means of encapsulating and containing the name space and scope of variables and methods.
private default protected public

Same class(defining class)

Yes Yes Yes Yes
Same package subclass No Yes Yes Yes
Same package non subclass No Yes Yes Yes
Different package subclass No No Yes Yes
Different package non subclass No No No Yes

         Rows indicate place from which want to gain access.

         public: Member is accessible anywhere the containing class is accessible. Least restrictive.

Use: For methods or constants that form part of the public API.

         protected: It is accessible to all classes within the package and also accessible within the body of any subclass of a class regardless of the package in which that subclass is defined.

Use: For subclass as a part of different package and cannot be changed without potentially breaking code that relies on them.

         default: It is accessible to code within all classes that are defined in the same package, but inaccessible outside the package. Also called package access.

Use: used by cooperating classes in same package

         private: Member is never accessible except within class. Hidden.

Keyword Effect Example
private Members are not accessible outside class. Making a constructor private prevents class being instantiated. Making a method private means that it can only be called from within the class. classFruit{private intgrams;private intcals_per_gram;privateFruit(){grams=55;cals_per_gram=0;}
None (package access) Members are accessible in classes in same package. A class can be given package access. classEmployee{String name;longsalary;static int total_emp;static voidclear(){total_emp=0;}}
protected Members are accessible in the package and in subclasses of this class. classEmp{protectedString name;protected longsalary;protected void give_raise(intamt){salary+=amt;}} 
public Members are accessible anywhere the class is accessible. public classEmp{public static voidmain(String[]args){}}

Interfaces  

Interface is a collection of constants and abstract methods. It is a specification without implementation.

public, static, final              by default public and abstract by default

         Contains instance methods not class methods

         All methods of an interface are implicitly public

         Cannot define instance fields

         Cannot be instantiated, does not define constructor

Rules

  • A class can implement any number of interfaces and any number of classes can implement interfaces.
  • If a class implements more than one interface, it must implement every method of each interface it implements. If not, class itself is abstract.
  • Each class is free to determine the details of its own implementation.
  • If interface is declared public then all methods implicitly become public.
  • If class implements two interfaces that declare the same method, then clients of either interface will use same method.

interface demoIF

{

void print(int param);

}

public class Client implements demoIF

{

public void print(int p)

{

System.out.println(p);

}

void non_if_method()

{

System.out.println(“non_if_method()”);

}

public static void main(String[] args)

{

Client c = new Client();

c.print(100);

}

}

Extending interfaces

One interface can inherit another by use of extends. This syntax is same as for inheriting classes.

A sub-interface inherits all abstract methods and constants of its super interface and can define new abstract methods and constants.

When a class implements an interface that inherits another interface, it must provide implementations for all methods defined within the interface inheritance chain.

Example

interface A

{

void m1();

void m2();

}

interface B extends A

{

void m3();

}

class MyClass implements B

{

public void m1()

{

System.out.println(“m1()”);

}

public void m2()

{

System.out.println(“m2()”);

}

public void m3()

{

System.out.println(“m3()”);

}

}

class IFextend

{

public static void main(String[] args)

{

MyClass obj = new MyClass();

obj.m1();

obj.m2();

obj.m3();

}

}

Other interesting Java related Posts you may like 🙂 :

What is Java? (clean-clouds.com)

Object-Oriented Programming Concepts (clean-clouds.com)

Java Language Fundamentals (clean-clouds.com)

Operators, Expressions and Control Structures in Java (clean-clouds.com)

Creating, Compiling and Running a Simple program in Java (clean-clouds.com)

Generics and Collections in Java (clean-clouds.com)

Applet and Swing in Java (clean-clouds.com)

JDBC in Java (clean-clouds.com)

Basic I/O in Java (clean-clouds.com)

Threads in Java (clean-clouds.com)

Packages in Java (clean-clouds.com)

Exceptions in Java (clean-clouds.com)

Using JavaDoc to document your Java Program (clean-clouds.com)

Java Coding Standards (clean-clouds.com)

Open Source ILS: Installation Guide for Koha on Ubuntu 11.10 or Ubuntu 11.04 or Ubuntu 10.10 or Ubuntu 10.04 LTS with MySQL 5 (clean-clouds.com)

REST and OO REST (clean-clouds.com)

Java Application in One JAR (clean-clouds.com)

Obfuscation in Java (clean-clouds.com)

Encryption~Hybrid Approach (clean-clouds.com)

Single Sign-On for Java and Web Applications

Bulletproof Java Code: A Practical Strategy for Developing Functional, Reliable, and Secure Java Code

Transforming a Generic Java IDE to Your Application Specific IDE:

The Java Virtual Appliance—No OS Required

BEA WebLogic® Operations Control: Application Virtualization for Enterprise Java

Enabling Rapid ROI: With Java™ – Based Business Intelligence Applications:

Advertisements

25 thoughts on “Object-Oriented Programming Concepts”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s