Class Examples

To model a car, encapsulate its attributes and behaviour into a class.

Model an animal, a real world object.


/**
* Cat.java
*/
public class Cat
{
// attributes
private String color;
private boolean pet;

// behaviour
public void pur() {
System.out.println("The cat purrrs.");
}

public boolean isPet() {
return pet;
}

public void set(boolean pet) {
this.pet = pet;
}

public String getColor() {
return color;
}

public void setColor(String clr) {
color = clr;
}
}

Model a concept, a mental construct.


/**
* Time.java
*/
public class Time {

// attributes
private long timeSinceEpoch;
private long timeInMillis;

// behaviour
public long timeNow() {
return timeInMillis;
}

public void setCurrentTime(long timeNow) {
timeInMillis = timeNow;
}

}

A notable principle of object-oriented programming is data hiding. The class variables representing the attributes are declared private, limiting their visibility to other classes.

A related concept is encapsulation: the grouping of attributes and methods into a class. The basic indivisible unit of execution in Java is a class.

Class


Objects in the world around us are of two kinds: physical objects and conceptual objects. All objects share two distinctive features: they all have attributes and they all exhibit some behaviour. 

The attributes are also called characteristics or properties. Examples of physical objects are: a cat, a piece of rock, or a person. Conceptual objects include a bank account, an institution or any idea that represents a non-physical entity. 

An object belongs to a type. The cat is a type of animal, the rock is a non-living thing and a bank account could be a savings or current account type.

In order to model an object in software, the attributes and behaviour of the object are considered. The attributes are represented as data members called variables. The behaviour is represented as methods. The attributes and the behaviour are wrapped up into a single unit called a class. 

A class therefore represents a type of object.

OOP! Java

This is the excerpt for your very first post.

This blog will feature concepts and design principles of the Java programming language as explored in the corporate training sessions. It is driven primarily by the requirements of the participants, hence the focus will be on code examples, backed up by textual explanations and visual content where possible. Features of the object-oriented programming paradigm will also figure from time to time.