Method calls and Multiple Constructor

Internal method calls:
Example:
public class Outer
{
String ostr = “Outer”;

static String osstr = “Static Outer”;

Outer()
{
System.out.println(ostr);
}

class Inner
{
String istr = “Inner”;

Inner()
{
System.out.println(istr + “\t” + Outer.this.ostr);
}
}

static class Inners
{
String isstr = “Static Inner”;

Inners()
{
System.out.println(isstr + “\t” + Outer.osstr);
}
}

static Inners mess()
{
return(new Inners());
}

public static void main(String args[])
{
Outer.Inner ob = new Outer().new Inner();

Outer.Inners obs = Outer.mess();
}
}
External method calls:
public class Artist
{
private String name;
private Song song;

public Artist(String name)
{
this.name = name;
}

public String getName()
{
return this.name;
}

public void setName(String newName)
{
this.name = newName;
}

public Song getSongs()
{
System.out.println(this.song.listSongs());
}

public void addSong(String song)
{
songs.storeSong(song);
}
}

Multiple Constructor:
A class can have multiple constructors that assign the fields in different ways. Sometimes it’s beneficial to specify every aspect of an object’s data by assigning parameters to the fields, but other times it might be appropriate to define only one or a few.

Spot sp1, sp2;

void setup() {
size(640, 360);
background(204);
noLoop();
// Run the constructor without parameters
sp1 = new Spot();
// Run the constructor with three parameters
sp2 = new Spot(width*0.5, height*0.5, 120);
}

void draw() {
sp1.display();
sp2.display();
}

class Spot {
float x, y, radius;

// First version of the Spot constructor;
// the fields are assigned default values
Spot() {
radius = 40;
x = width*0.25;
y = height*0.5;
}

// Second version of the Spot constructor;
// the fields are assigned with parameters
Spot(float xpos, float ypos, float r) {
x = xpos;
y = ypos;
radius = r;
}
void display() {
ellipse(x, y, radius*2, radius*2);
}

}

 

Debugger

 Debugger:
A special program used to find errors (bugs) in other programs. A debugger allows a programmer to stop a program at any point and examine and change the values of variables.

Setting breakpoints:
Breakpoints are set with the break command (abbreviated b). The debugger convenience variable `$bpnum’ records the number of the breakpoint you’ve set most recently; see Convenience variables, for a discussion of what you can do with convenience variables.
You have several ways to say where the breakpoint should go.
break function
Set a breakpoint at entry to function function. When using source languages that permit overloading of symbols, such as C++, function may refer to more than one possible place to break. See section Breakpoint menus, for a discussion of that situation.
break +offset
break -offset
Set a breakpoint some number of lines forward or back from the position at which execution stopped in the currently selected stack frame. (See section Frames, for a description of stack frames.)
break linenum
Set a breakpoint at line linenum in the current source file. The current source file is the last file whose source text was printed. The breakpoint will stop your program just before it executes any of the code on that line.
break filename:linenum
Set a breakpoint at line linenum in source file filename.
break filename:function
Set a breakpoint at entry to function function found in file filename. Specifying a file name as well as a function name is superfluous except when multiple files contain similarly named functions.
break *address
Set a breakpoint at address address. You can use this to set breakpoints in parts of your program which do not have debugging information or source files.
break
When called without any arguments, break sets a breakpoint at the next instruction to be executed in the selected stack frame (see section Examining the Stack). In any selected frame but the innermost, this makes your program stop as soon as control returns to that frame. This is similar to the effect of a finish command in the frame inside the selected frame–except that finish does not leave an active breakpoint. If you use break without an argument in the innermost frame, GDB stops the next time it reaches the current location; this may be useful inside loops.
GDB normally ignores breakpoints when it resumes execution, until at least one instruction has been executed. If it did not do this, you would be unable to proceed past a breakpoint without first disabling the breakpoint. This rule applies whether or not the breakpoint already existed when your program stopped.
break … if cond
Set a breakpoint with condition cond; evaluate the expression cond each time the breakpoint is reached, and stop only if the value is nonzero–that is, if cond evaluates as true. `…’ stands for one of the possible arguments described above (or no argument) specifying where to break. See section Break conditions, for more information on breakpoint conditions.
tbreak args
Set a breakpoint enabled only for one stop. args are the same as for the break command, and the breakpoint is set in the same way, but the breakpoint is automatically deleted after the first time your program stops there. See section Disabling breakpoints.
hbreak args
Set a hardware-assisted breakpoint. args are the same as for the break command and the breakpoint is set in the same way, but the breakpoint requires hardware support and some target hardware may not have this support. The main purpose of this is EPROM/ROM code debugging, so you can set a breakpoint at an instruction without changing the instruction. This can be used with the new trap-generation provided by SPARClite DSU and some x86-based targets. These targets will generate traps when a program accesses some data or instruction address that is assigned to the debug registers. However the hardware breakpoint registers can take a limited number of breakpoints. For example, on the DSU, only two data breakpoints can be set at a time, and GDB will reject this command if more than two are used. Delete or disable unused hardware breakpoints before setting new ones (see section Disabling). See section Break conditions.
thbreak args
Set a hardware-assisted breakpoint enabled only for one stop. args are the same as for the hbreak command and the breakpoint is set in the same way. However, like the tbreak command, the breakpoint is automatically deleted after the first time your program stops there. Also, like the hbreak command, the breakpoint requires hardware support and some target hardware may not have this support. See section Disabling breakpoints. See also Break conditions.
rbreak regex
Set breakpoints on all functions matching the regular expression regex. This command sets an unconditional breakpoint on all matches, printing a list of all breakpoints it set. Once these breakpoints are set, they are treated just like the breakpoints set with the break command. You can delete them, disable them, or make them conditional the same way as any other breakpoint.
The syntax of the regular expression is the standard one used with tools like `grep’. Note that this is different from the syntax used by shells, so for instance foo* matches all functions that include an fo followed by zero or more os. There is an implicit .* leading and trailing the regular expression you supply, so to match only functions that begin with foo, use ^foo.
When debugging C++ programs, rbreak is useful for setting breakpoints on overloaded functions that are not members of any special classes.
info breakpoints [n]
info break [n]
info watchpoints [n]
Print a table of all breakpoints, watchpoints, and catchpoints set and not deleted, with the following columns for each breakpoint:
Breakpoint Numbers
Type
Breakpoint, watchpoint, or catchpoint.
Disposition
Whether the breakpoint is marked to be disabled or deleted when hit.
Enabled or Disabled
Enabled breakpoints are marked with `y’. `n’ marks breakpoints that are not enabled.
Address
Where the breakpoint is in your program, as a memory address.
What
Where the breakpoint is in the source for your program, as a file and line number.
If a breakpoint is conditional, info break shows the condition on the line following the affected breakpoint; breakpoint commands, if any, are listed after that.
info break with a breakpoint number n as argument lists only that breakpoint. The convenience variable $_ and the default examining-address for the x command are set to the address of the last breakpoint listed (see section Examining memory).

Primitive types and object types

By now, we are used to distinguishing between primitive values and objects. We know, for instance, that subtyping is provided for object types but not primitive types. In this chapter, we will focus a bit more in-depth on the differences between these two kinds of values. We will look at special types, called wrapper classes, that provide bridges between primitive values and objects. We will also study the difference between the way these two kinds of values are stored in memory, and the implication this difference has for the assignment statement. This will lead us to the concept of garbage collection, an important feature of Java.
Storing Object Values and Variables:
Object values and variables, however, are stored differently. Consider:
Integer I = new Integer (5);
Double D = new Double(5.5);
As before, both values and the variables are allocated memory. However, each assignment copies into the variable’s block, not the contents of the value block, but instead its address. All Java addresses are 1 word long, so all variables are allocated a 1-word block, regardless of their types. Thus, both the Double variable, D, and the Integer variable, I, are the same size, which was not the case with the double variable, d, and integer variable, i, we saw above.

All objects, however, are not of the same size. When a new object is created, a composite memory block consisting of a series of consecutive blocks, one for each instance variable of the object, is created. Thus, assuming an Integer has a single int instance variable, a block consisting of a single integer variable is created. Similarly, for a Double instance, a block consisting of a single double instance variable is created. The sizes of the two objects are different because of the difference in the sizes of their instance variable. However, in both cases, the object block consists of a single variable.

Now consider the following class:
public class APoint implements Point {
int x,y;
public APoint (int initX, int initY) {
x = initX; y = initY;
}
public void setX(int newVal) {
x = newVal;
}

}
The figure below shows how the following assignment of an instance of this class is processed:
Point P = new APoint( 50, 100) ;
An instance of this class has a memory block consisting of two consecutive int blocks, as shown in the figure.

 

Object Values and Variables:
Now consider the following subclass of APoint, called ABoundedPoint, that declares two APoint instance variables defining a rectangular area defining user-specified bounds of the point:
public class ABoundedPoint extends APoint {
APoint upperLeftCorner, lowerRightCorner;
public ABoundedPoint (int initX, int initY, Point initUpperLeftCorner, Point initLowerRightCorner) {
super(initX, initY);
upperLeftCorner = initUpperLeftCorner;
lowerRightCorner = initLowerRightCorner;
}

}
Recall that an instance has not only the instance variables defined in its class but also those defined the superclasses of its class. Therefore, an instance of ABoundedPoint, has a memory block consisting of memory blocks of four variables, two int variables, each of size 1 word, inherited from APoint, and two object variables, each also of size 1 word, defined in ABoundedPoint.

 

 

Class diagrams VS object diagrams

⦁ A class diagram is a graph of Classifier elements connected by their various static relationships. Note that a “class” diagram may also contain interfaces, packages, relationships, and even instances, such as objects and links. Perhaps a better name would be “static structural diagram”, but “class diagram” is shorter and well established.
⦁ An object diagram is a graph of instances, including objects and data values. A static object diagram is an instance of a class diagram; it shows a snapshot of the detailed state of a system at a point in time. The use of object diagrams is fairly limited, mainly to show examples of data structures.
⦁ Tools need not support a separate format for object diagrams. Class diagrams can contain objects, so a class diagram with objects and no classes is an “object diagram.” The phrase is useful, however, to characterize a particular usage achievable in various ways.

 

Abstraction and Modularization

 

Abstraction:

Abstraction in Java or Object oriented programming is a way to segregate implementation from interface and one of the five fundamentals along with Encapsulation, Inheritance, Polymorphism, Class and Object.  Abstraction in Java is achieved by using interface and abstract class in Java. An interface or abstract class is something which is not concrete, something which is incomplete. In order to use interface or abstract class we need to extend and implement abstract method with concrete behavior. One example of Abstraction is creating interface to denote common behavior without specifying any details about how that behavior works e.g. You create an interface called Server which has start() and stop() method. This is called abstraction of Server because every server should have way to start and stop and details may differ. As I said earlier Abstraction in Java is implemented using abstract class and interface as discussed in next section. In fact What is abstraction in Java, Difference between Abstraction and Encapsulation  is also a very popular core Java interview because strong OOPS skill is one of the primary requirement for Java developers.
Abstraction Example:
A Car has Engine, wheels and many other parts. When we write all the properties of the Car, Engine, and wheel in a single class, it would look this way:
public class Car {

int price;
String name;
String color;
int engineCapacity;
int engineHorsePower;

String wheelName;
int wheelPrice;

void move(){
//move forward
}
void rotate(){
//Wheels method
}

void internalCombustion(){
//Engine Method
}

}
In the above example, the attributes of wheel and engine are added to the Car type. As per the programming, this will not create any kind of issues. But when it comes to maintenance of the application, this becomes more complex.
Abstraction has three advantages:
⦁ By using abstraction, we can separate the things that can be grouped to another type.
⦁ Frequently changing properties and methods can be grouped to a separate type so that the main type need not under go changes. This adds strength to the OOAD principle -“Code should be open for Extension but closed for Modification”.
⦁ Simplifies the representation of the domain models.
Applying the abstraction with composition, the above example can be modified as given below:

public class Car {

Engine engine = new Engine();
Wheel wheel = new Wheel();

int price;
String name;
String color;

void move(){
//move forward
}

}

public class Engine {
int engineCapacity;
int engineHorsePower;

void internalCombustion(){
//Engine Method
}

}

public class Wheel {
String wheelName;
int wheelPrice;

void rotate(){
//Wheels method
}

}
You can see that the attributes and methods related to the Engine and Wheel are moved to the respective classes.
Engine and Wheel are referred from the Car type. When ever an instance of Car is created, both Engine and Wheel will be available for the Car and when there are changes to these Types(Engine and Wheel), changes will only be confined to these classes and will not affect the Car class.

Modularization:

Modular programming is the approach where the application code is subdivided into separate subprograms, with each running a specific function or subroutine. These chunks of code can be split up and worked on by multiple programmers, teams or by an individual over time, with each chunk of code dedicated to doing on specific task. These tasks also become recyclable, as they can be tweaked to fit into other programs. This keeps a programmer from having to write a similar task again in the future if a module already exists in another location that can handle the task at hand. The programmer can simply pull out an existing module, tweak it and insert it into the new program he/she is working on, saving time and energy in his/her work.
If creating a program to track attendance in multiple classes at a school, the master program would achieve this task for all students in all classes, throughout the year. If the application were to be broken down into modules, one module might track the attendance for a specific student over the course of the year. Another module might group the student attendance records by class, such as Geology or Science class, or even sophomore class, junior class, or the class of 2009. The modularization of the program allows it to be applied to various scenarios, students, years, schools, or anywhere attendance needs to be tracked, simply by tweaking the existing code and making it fit into the new scenario.

 

haris dic.

import java.util.ArrayList;

import java.util.Iterator;

import java.util.*;

/**

* class SpellChecker for a text application (for example, a word processor, or something similar).

*

* @author (Waqar Ahmad 116-bscs-2010,Haris zeeshan 105-bscs-2010,Ammar Hassan 60-bscs-2012,Ammar zaheer 69-bscs-2009)

* @version (1.0)

*/

public class SpellChecker

{

DictReader dr;

private ArrayList<String> dic;

private ArrayList<String> listofWords;

/**

* Constructor for objects of class SpellChecker

*/

public SpellChecker()

{

dr=new DictReader(“words.txt”);

dic=dr.getDictionary();

listofWords=new ArrayList<String>();

}

//########## Base Task Level 1 impelements by Ammar hassan and Ammar zaheer

/**

* This method returns the number of words in the dictionary.

*/

public int numberOfWords()

{

return dic.size();

}

/**

* This method returns true, if (and only if) the given word is found in the dictionary.

*/

public boolean isKnownWord(String word)

{

if(dic.contains(word))

return true;

else

return false;

}

/**

* This method returns true if (and only if) all words in the given list are found in the dictionary.

*/

public boolean allKnown(ArrayList<String> words)

{

for(int i=0;i<words.size();i++)

{

if(!isKnownWord(words.get(i).toLowerCase()))

return false;

}

return true;

}

//######### Base Task Level 2 impelements by Waqar Ahmad & Haris zeeshan

/**

* This method returns a list of all words from the dictionary that start with the given prefix.

*/

public ArrayList<String> wordsStartingWith(String prefix)

 

{

Iterator <String>it=dic.iterator();

while(it.hasNext())

{

String ch=it.next();

if(ch.startsWith(prefix.toLowerCase()) || ch.startsWith(prefix.toUpperCase()))

{

listofWords.add(ch);

}

}

return listofWords;

}

/**

* This method returns a list of all words from the dictionary that include the given substring.

*/

public ArrayList<String> wordsContaining(String text)

{

String s1;

ArrayList<String> wordsList=new ArrayList();

for(int i=0;i<dic.size();i++)

{

s1=dic.get(i);

if (s1.toLowerCase().contains(text.toLowerCase()) || s1.toUpperCase().contains(text.toUpperCase()))

{

wordsList.add(s1);

}

}

return wordsList;

}

//######### Base tasks (level 3) impelements by Waqar Ahmad

/**

* Insert the given word into the dictionary if it does not exist in it.

* The word should only be inserted if it does not already exist in the dictionary.

*/

public void insert(String newWord)

{

boolean isExist=isKnownWord(newWord);

if(isExist==false)

{

dic.add(newWord);

}

Collections.sort(dic);

}

/**

* Remove the given word from the dictionary.

* If the word was successfully removed, return true.

* If not (for example it did not exist) return false.

*/

public boolean remove(String newWord)

{

if(dic.contains(newWord))

{

int a=dic.indexOf(newWord);

dic.remove(a);

return true;

}

else

return false;

}

/**

* Method use to write ArrayList on a text File

*/

public void save()

{

dr.save(dic);

}

//#########   Challenge tasks  co-effort of group on these Methods

/**

* Return true if (and only if) the given word is a palindrome

*/

public boolean isPalindrome(String word)

{

int a=word.length()-1;

for(int i=0;i<=a/2;i++)

{

if(word.toLowerCase().charAt(i)==word.toLowerCase().charAt(a))

{    a–;

}

else

{

return false;

}

}

if(dic.contains(word))

{

System.out.println(“Dictionary not Contains Given Word !!”);

}

else

{

System.out.println(“word dose not exist in dic”);

}

return true;

}

/**

* Return a list of all words that are anagrams of the given word.

* Anagrams are treated as case-insensitive.

*/

public ArrayList<String> anagrams(String word)

{

// trying to complete ,but Cannot achive this goal

return dic  ;

}

/**

* . Return a list of words that are in one of the dictionaries, but not in the other.

*   pass another dictionary as a parameter

*/

public ArrayList<String> difference(ArrayList<String> dictionary)

{

ArrayList <String> difWords=new <String> ArrayList();

for(int index=0;index<=dictionary.size();index++)

{   String word=dictionary.get(index);

if(!dic.contains(word))

{

difWords.add(word);

}

}

return difWords;

}

}

Oop in java (post 3)

  • Creating Class

Class definition:

Assessor modifier Class CLas_Name

{

Fields;

Constructor;

Methods;

}

Fields:

you can set up variables outside of methods that all the methods in          your class  can see. These are known as Field variables (or Instance variables). You set them up in exactly the same way as any other variable.

 

Example:

Constructors:

java constructor has the same name as the name of the class to which it belongs. Constructor’s syntax does not include a return type, since constructors never return a value.

Constructors may include parameters of various types. When the constructor is invoked using the new operator, the types must match those that are specified in the constructor definition.

Java provides a default constructor which takes no arguments and performs no special actions or initializations, when no explicit constructors are provided.

The only action taken by the implicit default constructor is to call the superclass constructor using the super() call. Constructor arguments provide you with a way to provide parameters for the initialization of an object.

Below is an example of a cube class containing 2 constructors. (one default and one parameterized constructor).

public class Cube1 { 

int length;

int breadth;

int height;

public int getVolume() {

return (length * breadth * height);

}

Cube1() {

length = 10;

breadth = 10;

height = 10;

}

Cube1(int l, int b, int h) {

length = l;

breadth = b;

height = h;

}

public static void main(String[] args) {

Cube1 cubeObj1, cubeObj2;

cubeObj1 = new Cube1();

cubeObj2 = new Cube1(10, 20, 30);

System.out.println(“Volume of Cube1 is : ” + cubeObj1.getVolume());

System.out.println(“Volume of Cube1 is : ” + cubeObj2.getVolume());

}

}

  Methods:

We clearly explain methods above.

 

  • Types of Statement

Assignment Statement:

An assignment statement in Java uses the assignment operator (=) to assign the result of an expression to a variable. In its simplest form, you code it like this:

variable = expression;

For example:

int a = (b * c) / 4;

compound assignment operator is an operator that performs a calculation and an assignment at the same time. All Java binary arithmetic operators (that is, the ones that work on two operands) have equivalent compound assignment operators:

Operator

Description

+= Addition and assignment
-= Subtraction and assignment
*= Multiplication and assignment
/= Division and assignment
%= Remainder and assignment

For example, the statement

a += 10;

is equivalent to

a = a + 10;

Condional Statement:

The && and || operators perform Conditional-AND and Conditional-OR operations on two Boolean expressions. These operators exhibit “short-circuiting” behavior, which means that the second operand is evaluated only if needed.

&& Conditional-AND
|| Conditional-OR

 

  • Types of Methods

Accessor methods:

An accessor method is used to return the value of a private field. It follows a naming scheme prefixing the word “get” to the start of the method name. For example let’s add accessor methods for firstname, middleNames and lastname:

   //Accessor for firstName
   public String getFirstName()
   {
     return firstName;
   }

 

Mutator methods:

A mutator method is used to set a value of a private field. It follows a naming scheme prefixing the word “set” to the start of the method name. For example, let’s add mutator fields for address and username:

   //Mutator for address
   public void setAddress(String address)
   {
     this.address = address;
   }

 

  • Types of Variables

Local variables:

local variable in Java is a variable that’s declared within the body of a method. Then you can use the variable only within that method. Other methods in the class aren’t even aware that the variable exists.

Here’s a program that uses a local variable:

public class HelloApp
{
    public static void main(String[] args)
    {
        String helloMessage;
        helloMessage = "Hello, World!";
        System.out.println(helloMessage);
    }
}

You don’t specify static on a declaration for a local variable. If you do, the compiler generates an error message and refuses to compile your program.

 

Field variable:

Variable that are declared as a member of a class. OR Variables declared outside any method/constructor but inside the class block. We discuss this above in detail.

 

Parameters:

A parameter is a variable that you pass in to a function. If you think back to math class, you spend a lot of time talking about f(x). In that case, “f” is the function and “x” is the parameter- something passed in to x that is going to change what the output of f gives you.

For example, look at the code you’ve been using in every single Java program you’ve written:

public static void main(String[] args)

That is a function that takes one argument- an array of Strings that’s called args. Then there’s also the way you write stuff to the console:
System.out.println(“Hello World”);
In that case, you have a function that takes one parameter. The value of that parameter is the string “Hello World”.

Oop in java (post 2)

  • Method

A method is just a chunk of code that does a particular job. But methods are set out in a certain way. You have a method header, and a method body. The header is where you tell Java what value type, if any, the method will return (an int value, a double value, a string value, etc). As well as the return type, you need a name for your method, which also goes in the header. You can pass values over to your methods, and these go between a pair of round brackets.

A simple Java method requires a minimum of three items:

Visibility : public, private, protected
Return Type: void, int, double, (etc.)
name: whatever you want to call the method

Visibility means who can access it. If it is public, anyone who has access to your class file can access the method. In some circumstances, this is perfectly fine. If the method is private, only the functions inside of that class can call the method. This is used as utility methods to do something you do not want just anyone who uses the class to do. Protected gives public function to all child classes.

Return type is void if you do not want the method to give you any data back. It would be used for such things as a method that prints out something. Any other return requires a return statement with the type of data it returns. For example, if you add two integers and want the results of that integer, your return type would be int.

Name of the method is anything you choose that is not already used in the class (unless you are overloading the method which is beyond the scope of this article)

If you want the method to do something with the data you supply it, you also need to include parameters within the ( ) You include what data type it is and give that parameter a name (ie: you are declaring a local variable for that method only)
examples:

access   return type   name   parameters
public     void             add     (int a, int b)

This would be written

public void add(int a, int b)
{
// do stuff here
}

Since the return type is void, you will have to write what you want the method to do inside of the method such as by printing it out from the method

public void add(int a, int b)
{
System.out.println(a+b);
}

  • Source Code:

Code that is written in high level language is called source code and in the context of java its called java code and its extension is .java and it’s not directly run on computer compiler is required to convert it in machine code.

  • IDE(BlueJ):

BlueJ is an integrated development environment (IDE) for the Java programming language, developed mainly for educational purposes, but also suitable for small-scale software development.

BlueJ was developed to support the learning and teaching of object-oriented programming, and its design differs from other development environments as a result. The main screen graphically shows the class structure of an application under development (in an UML-like diagram), and objects can be interactively created and tested. This interaction facility, combined with a clean, simple user interface, allows easy experimentation with objects under development. Object-oriented concepts (classes, objects, communication through method calls) are represented visually and in its interaction design in the interface.

OOP in Java

 

Java is an Object Oriented Language. As a language that has the Object Oriented feature Java supports the following fundamental concepts:

  • Polymorphism
  • Inheritance
  • Encapsulation
  • Abstraction
  • Classes
  • Objects
  • Instance
  • Method
  • Message Parsing

 

  • Class:

In the real world, you’ll often find many individual objects all of the same kind. There may be thousands of other bicycles in existence, all of the same make and model. Each bicycle was built from the same set of blueprints and therefore contains the same components. In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles. A class is the blueprint from which individual objects are created.

The following Bicycle class is one possible implementation of a bicycle:

 

class Bicycle {

 

int cadence = 0;

int speed = 0;

int gear = 1;

 

void changeCadence(int newValue) {

cadence = newValue;

}

 

void changeGear(int newValue) {

gear = newValue;

}

 

void speedUp(int increment) {

speed = speed + increment;

}

 

void applyBrakes(int decrement) {

speed = speed – decrement;

}

 

void printStates() {

System.out.println(“cadence:” +

cadence + ” speed:” +

speed + ” gear:” + gear);

}

}

 

  • Object:

Concept of object:

A typical Java program creates many objects, which as you know, interact by invoking methods. Through these object interactions, a program can carry out various tasks, such as implementing a GUI, running an animation, or sending and receiving information over a network. Once an object has completed the work for which it was created, its resources are recycled for use by other objects.

Creating Object:

Here’s a small program, called CreateObjectDemo, that creates three objects: one Point object and two Rectangle objects. You will need all three source files to compile this program.


public class CreateObjectDemo {

public static void main(String[] args) {

// Declare and create a point object and two rectangle objects.
Point originOne = new Point(23, 94);
Rectangle rectOne = new Rectangle(originOne, 100, 200);
Rectangle rectTwo = new Rectangle(50, 100);

// display rectOne's width, height, and area
System.out.println("Width of rectOne: " + rectOne.width);
System.out.println("Height of rectOne: " + rectOne.height);
System.out.println("Area of rectOne: " + rectOne.getArea());

// set rectTwo's position
rectTwo.origin = originOne;

// display rectTwo's position
System.out.println("X Position of rectTwo: " + rectTwo.origin.x);
System.out.println("Y Position of rectTwo: " + rectTwo.origin.y);

// move rectTwo and display its new position
rectTwo.move(40, 72);
System.out.println("X Position of rectTwo: " + rectTwo.origin.x);
System.out.println("Y Position of rectTwo: " + rectTwo.origin.y);
}
}

This program creates, manipulates, and displays information about various objects. Here’s the output:

Width of rectOne: 100
Height of rectOne: 200
Area of rectOne: 20000
X Position of rectTwo: 23
Y Position of rectTwo: 94
X Position of rectTwo: 40
Y Position of rectTwo: 72