|< C++ Namespace 2 | Main | STL - C++ Templates >| Site Index | Download |


 

 

 

OBJECT ORIENTED PROGRAMMING:

FROM  C++  TO  JAVA  AND  C++ .NET

 

 

 

 

 

The programming environment for this session:

  1. Java Compiler/IDE: JGRASP

  2. Project: Just Java Old Plain Code

  3. Project Settings: None, all default settings

  4. OS: Win Xp Pro SP2 + updates + patches…, 2GB RAM, Intel Core 2 Duo…

 

 

 

 

 

 

  • Well, where are you going after learning the C++, its capabilities and object oriented features? Other than building new big applications using C++, let see how C++ object oriented principles has been used in Java and later, Visual C++ .NET (and other .NET family too). You should be familiar with the Java program structure, class and object if you already grasped all the C++ object oriented fundamentals.

  • The following are Java console applications programs examples based on the questions and answers. Hopefully you will appreciate how the C++ has been used to make programming more productive and shrinking the gap between codes and the real world objects. There is nothing new except the Java implementation itself and try figure out the similarities that you have learned in C++. Enjoy!

  1. Write the definition of a class that has the following properties:

  1. The name of the class Secret

  2. The class has four data members: name (String), age (int), weight (int) and height (double)

  3. The class has the following methods:

  1. print  - outputs the values of all data members with appropriate titles.

  2. setName – method to set name to a new value

  3. setWeight – method to set the weight to a new value

  4. setHeight - method to set height to a new value

  5. getName - method to return the name

  6. getAge - method to return the age

  7. getWeight - method to return the weight

  8. getHeight - method to return the height

  9. default constructor – the default value of name is the empty string “”, the default values for age, weight and height are 0.

  10. constructor with parameters – sets the values of the data name, age, weight and height to the values specified by user

  1. Write the definitions of the methods of class Secret as described in part c.

 

Answer: This is just a working java program skeleton of class definition and object instantiation.

// this is a Java package where all the related classes (built-in)

// reside. For every class, there are many methods that we can invoke.

// In this case we are going to use the Scanner class

import java.util.Scanner;

 

//---------------------------------------------------------

// class Secret, nothing is secret here...

//---------------------------------------------------------

 

public class Secret

{

   // data declarations, variables with their own data types

   // initialized with values that will be used as default constructor's

   // values if there is no one to be found...initialized values

   // shown are defaults

   String name = "";

   int age = 0, weight = 0;

   double height = 0.0;

 

   // constructor that will overwrite the default one...

   // the name is same as the class without any return type

   public Secret(String coname, int coage, int coweight, double coheight)

   {

// using a pre-defined class, instantiating a new Scanner object

Scanner readdata = new Scanner(System.in);

 

// invoking the print() method of System.out object

System.out.print("Enter your name: ");

// invoking the nextLine() method of Scanner class (System.in object)

coname = readdata.nextLine();

setName(coname);

System.out.print("Enter your age: ");

coage = readdata.nextInt();

setAge(coage);

System.out.print("Enter your weight: ");

coweight = readdata.nextInt();

setWeight(coweight);

System.out.print("Enter your height: ");

coheight = readdata.nextDouble();

setHeight(coheight);

print();

}

 

//---------------------------------------------------------

// The following methods will be used when the instantiated

// object call them from the main().....

// in this program, however call from main() may be overwritten

// by the constructors....

//---------------------------------------------------------

 

// setName method() - set name to a new value

public void setName(String yourname)

{

      name = yourname;

}

 

// setAge method() - set the age to a new value

public void setAge(int yourage)

{

      age = yourage;

}

 

// setWeight method() - set the weight to a new value

public void setWeight(int yourweight)

{

      weight = yourweight;

}

 

// setHeight method() - set the height to a new value

public void setHeight(double yourheight)

{

      height = yourheight;

}

 

// getName method() - return the name

public String getName()

{

      return name;

}

 

// getAge method() - return the age

public int getAge()

{

      return age;

}

 

// getWeight method() - return the weight

public int getWeight()

{

      return weight;

}

 

// getHeight method() - return the height

public double getHeight()

{

      return height;

}

 

// print method() - output all data to standard output

public void print()

{

      System.out.println();

      System.out.println("Your name is: " + getName() + ".");

      System.out.println("Your age is: " + getAge() + " years old.");

      System.out.println("Your weight is: " + getWeight() + " kgs.");

      System.out.println("Your height is: " + getHeight() + " cms.");

}

 

// main() method - the start of this program execution point

public static void main(String[] args)

{

      // instantiate an object of type Secret class

      // giving some dummy values that will be overwritten by

      // the 'Constructor with parameters'.

      // this instantiation will invoke Constructor with parameters

      Secret mysecret = new Secret("Nazri",30,56,165);

      // other codes.....

}

}

A Sample output:

 

Enter your name: Ahmad Nazri bin Zainol

Enter your age: 48

Enter your weight: 53

Enter your height: 165

 

Your name is: Ahmad Nazri bin Zainol.

Your age is: 48 years old.

Your weight is: 53 kgs.

Your height is: 165.0 cms.

 

Enter your name: Meg Ryan Jr.

Enter your age: 40

Enter your weight: 50

Enter your height: 170

 

Your name is: Meg Ryan Jr..

Your age is: 40 years old.

Your weight is: 50 kgs.

Your height is: 170.0 cms.

 

  1. Implement a class Rectangle that has methods getArea(), getPerimeter() and getDiagonal(). In the constructor, supply the length and width of the rectangle. Write a program that asks the user for the length and width of a rectangle. Then creates an object of Rectangle and prints its area, perimeter and diagonal length. (Use the Pythagorean formula to calculate length of the diagonal)

 

Answer: Another user defined class and object with 3 methods that do their own specific tasks.

import java.util.Scanner;

import java.text.DecimalFormat;

 

//---------------------------------------------------------

// class Rectangle: Area, Perimeter and Diagonal

//---------------------------------------------------------

// For rectangles with the sides a, b, is:

// area = a * b

// perimeter = 2*(a + b)

// diagonal = root of ((a*a)+(b*b))

 

public class Rectangle

{

   // member variables, used as default constructor values

   // if constructor not provided...

   double   height = 0.0 ;

   double   width = 0.0;

 

   // constructor

   Rectangle(double h, double w)

   {

      height = h;

      width = w;

   }

 

   // get the rectangle perimeter

   public double getPerimeter(double h, double w)

   {

      return   2*(h+w);

   }

 

    // get the rectangle area

   public double getArea(double h, double w)

   {

      return   (h*w);

   }

 

     // get the rectangle diagonal

   public double getDiagonal(double h, double w)

   {

      return   Math.sqrt(((h*h)+(w*w)));

   }

 

   // main() method - the start of this program execution point

   public static void main(String[] args)

   {

      double recheight = 0.0, recwidth = 0.0;

 

      // instantiate a standard input object

      Scanner readuserinput = new Scanner(System.in);

      // prompt user for rectangle's height and width

      System.out.print("Enter rectangle height and width (e.g: 10 10): ");

      // read and store rectangle's height and width

      recheight = readuserinput.nextDouble();

      recwidth = readuserinput.nextDouble();

      // instantiate and initialize the myrectangle object

// of type rectangle class

Rectangle myrectangle = new Rectangle(recheight, recwidth);

// do some formatting for the double

DecimalFormat fmt = new DecimalFormat("0.##");

// print rectangle's area, perimeter and diagonal to standard output

System.out.println("The rectangle area is: " + fmt.format(myrectangle.getArea(recheight,recwidth)));

System.out.println("The rectangle perimeter is: " + fmt.format(myrectangle.getPerimeter(recheight,recwidth)));

System.out.println("The rectangle diagonal is: " + fmt.format(myrectangle.getDiagonal(recheight,recwidth)));

}

}

A Sample outputs:

 

Enter rectangle height and width (e.g: 10 10): 10 10

The rectangle area is: 100

The rectangle perimeter is: 40

The rectangle diagonal is: 14.14

 

Enter rectangle height and width (e.g: 10 10): 12.5 10.5

The rectangle area is: 131.25

The rectangle perimeter is: 46

The rectangle diagonal is: 16.32

 

Enter rectangle height and width (e.g: 10 10): 50.2 21.7

The rectangle area is: 1089.34

The rectangle perimeter is: 143.8

The rectangle diagonal is: 54.69

  1. Define a class named MyDay that implements the day of the week in a program. The class MyDay should store the day, such as Sun for Sunday. The program should be able to perform the following operations on an object of the type MyDay:

  1. Set the day.

  2. Print the day.

  3. Return the day.

  4. Return the next day.

  5. Return the previous day.

 

The class should also have the appropriate constructor. Write a program to test all the operations for class MyDay as described in a. to e. above.

 

Answer: Day class and object manipulation.

 

import java.util.*;

 

//------------------------------------------------------------------

// MyDay class. Playing with day of week...

//------------------------------------------------------------------

 

public class MyDay

{

      // instantiate standard input object

      static Scanner readinput = new Scanner(System.in);

 

      // member variable, private by default

      String day;

 

      // constructor with "Sunday" value

      public MyDay(String day)

      {

         day = "Sunday";

      }

     

   // set the day

      public void setDay(String theDay)

      {

         day = theDay;

      }

 

      // print or return the day

      public String getDay()

      {

         return day;

      }

 

   // print the day, looks unnecessary

      public void printDay()

      {

         System.out.println("When printing, your day is " + day);

      }

 

      // return the next day

      public String getNextDay()

      {

         // using direct comparison will fail as day == "Saturday"?

         // so use compareTo() method...

         if((day.compareTo("Saturday") == 0) || (day.compareTo("Sat") == 0))

            return ("Sunday");

         else if((day.compareTo("Sunday") == 0) || (day.compareTo("Sun") == 0))

            return ("Monday");

         else if((day.compareTo("Monday") == 0) || (day.compareTo("Mon") == 0))

            return ("Tuesday");

         else if((day.compareTo("Tuesday") == 0) || (day.compareTo("Tue") == 0))

            return ("Wednesday");

         else if((day.compareTo("Wednesday") == 0) || (day.compareTo("Wed") == 0))

            return ("Thursday");

         else if((day.compareTo("Thursday") == 0) || (day.compareTo("Thu") == 0))

            return ("Friday");

         else if((day.compareTo("Friday") == 0) || (day.compareTo("Fri") == 0))

            return ("Saturday");

         else

            return ("\"Opps Error lol!\"");

      }

 

      // return the previous day

      public String getPreDay()

      {

         if((day.compareTo("Friday") == 0) || (day.compareTo("Fri") == 0))

            return ("Thursday");

         else if((day.compareTo("Thursday") == 0) || (day.compareTo("Thu") == 0))

            return ("Wednesday");

         else if((day.compareTo("Wednesday") == 0) || (day.compareTo("Wed") == 0))

            return ("Tuesday");

         else if((day.compareTo("Tuesday") == 0) || (day.compareTo("Tue") == 0))

            return ("Monday");

         else if((day.compareTo("Monday") == 0) || (day.compareTo("Mon") == 0))

            return ("Sunday");

         else if((day.compareTo("Sunday") == 0) || (day.compareTo("Sun") == 0))

            return ("Saturday");

         else if((day.compareTo("Saturday") == 0) || (day.compareTo("Sat") == 0))

            return ("Friday");

         else

            return ("\"Opps Error lol!\"");

      }

 

      // main execution point

      public static void main (String args[])

      {

             // One of its weakness is the case sensitive: sun, Sunday, sunday, SuNdAy...

             // need more codes to avoid this case sensitiveness...

             // instantiate testday object of type MyDay class

             // with "Sun" as initial value....

              MyDay testday = new MyDay("Sun");

              // prompt user to set his/her day

              System.out.print("Enter day to set your day: ");

              // read and store user's day

              String storeday = readinput.nextLine();

              // invoke setDay() method to set a day defined by user

              testday.setDay(storeday);

              // invoke getDay() method to get a day

              System.out.println("Your day is " + testday.getDay());

              // test printing by invoking printDay() method

              testday.printDay();

              // invoke getPreDay() method to get the previous day

              System.out.println("Your previous day is " + testday.getPreDay());

              // invoke getNextDay() method to get the next day

              System.out.println("Your next day is " + testday.getNextDay());

      }

}

 

A Sample outputs:

 

Enter day to set your day: Wednesday

Your day is Wednesday

When printing, your day is Wednesday

Your previous day is Tuesday

Your next day is Thursday

 

Enter day to set your day: Sat

Your day is Sat

When printing, your day is Sat

Your previous day is Friday

Your next day is Sunday

 

Enter day to set your day: sun

Your day is sun

When printing, your day is sun

Your previous day is "Opps Error lol!"

Your next day is "Opps Error lol!"

 

Enter day to set your day: Saturday

Your day is Saturday

When printing, your day is Saturday

Your previous day is Friday

Your next day is Sunday

 

tenouk fundamental of C++ object oriented tutorial

 

 

 

 

 

 

 

 

 

 

|< C++ Namespace 2 | Main | STL - C++ Templates >| Site Index | Download |