Question

a]using appropriate programming examples differentiate between cohesion and coupling[10marks] b]Write a java program that requests a...

a]using appropriate programming examples differentiate between cohesion and coupling[10marks]

b]Write a java program that requests a user to input 2 numbers then find the sum,difference and product of the inputed numbers [15marks]

c]Public,Private,Protected ,static and final are access modifiers ,outline their individual effects when prepended to methods[15marks]

d]Discuss the importance of the Exception class including examples of specific execeptions[10marks]

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Hi please find the complete answer

If you have any query please let me know first i will give resolution

===========================================

Answer a

Coupling

Coupling refers to the extent to which a class knows about the other class.

there are two type of coupling

1- Tightly Coupling

2- Loose Coupling

Tightly Coupling

If a class A has the public data members and another class B is accessing these data members of a class A directly using the dot operator(which is possible because data members were declared public), the two classes are said to be tightly coupled

class A

{

public String name;

public String getName()

{

//Checking a valid access to "name"

if(name!=null)

return name;

else

return"not initiaized";

}

public void setName(String s)

{

//Checking a valid setting to "name"

if (s==null)

{

System.out.println("You can't initialized name to a null");

}

}

} //Class A ends

class B

{

public static void main(String... ar)

{

Names ob= new Names();

//Directly setting the value of data member "name" of class A, due to tight coupling between the two classes

ob.name=null;  

//Direct access of data member "name" of class A, due to tight coupling between two classes

System.out.println("Name is " + ob.name);   

}

}

Output = Name is null

Class A has an instance variable, name, which is declared public.

Class A has two public getter and setter methods which check for a valid access and a valid setting of data member - name.

Class B creates an object of Names class and sets the value of its data member(name) to null and accesses it value directly by the dot operator, because it was declared public.

Hence, the checks implemented in getName() and setName() methods of class Names, to access and set the data member's value of class A are never called and are rather, bypassed. It shows class A is tighly coupled to class B, which is a bad design, compromising the data security checks

===============================================

Loose Coupling

A good application designing is creating an application with loosely coupled classes by following proper encapsulation, i.e. by declaring data members of a class with private access and forcing other classes to access them only through public getter, setter methods.

//Loose coupling

class A

{

//data member "name" is declared private to implement loose coupling.

private String name;

public String getName()

{

//Checking a valid access to name

if(name!=null)

return name;

else

return"not initiaized";

}

public void setName(String s)

{

//Checking a valid setting to name

if (s==null)

{

System.out.println("You can't initialize name to a null");

}

}

}

class B

{

public static void main(String... ar)

{

A ob= new A();

//Calling setter method, as the direct access of "name" is not possible i.e. loose coupling between classes

ob.setName(null);

//Calling getter method, as the direct access of "name" is not possible i.e. loose coupling

System.out.println("Name is " + ob.getName());   

}

}

Output is

You can't initialized name to a null

Name is not initiaized

Class A has an instance variable, name, which is declared private.

Class A has two public getter and setter methods> methods which check for a valid access and a valid setting of data member - name.

Class B creates an object of class A, calls the getName() and setName() methods and their checks are properly executed before the value of instance member, name is accessed or set. It shows class A is loosely coupled to class B, which is a good programming design.

===================================

Cohesion

Cohesion refers to the extent to which a class is defined to do a specific specialized task. A class created with high cohesion is targeted towards a single specific purpose, rather than performing many different specific purposes.

there are two type of cohesion

1- Low Cohesion

2- High Cohesion

Low Cohesion

When a class is designed to do many different tasks rather than focussing on a single specialized task, this class is said to be a "low cohesive" class. Low cohesive class are said to be badly designed leading to a hard time at creating, maintaining and updating them

class PlayerDatabase

{

public void connectDatabase();

public void printAllPlayersInfo();

public void printSinglePlayerInfo();

public void printRankings()

public void closeDatabase();

}

Here, we have a class PlayerDatabase which is performing many different tasks like connecting to a database, printing the information of all the players, printing an information of a singe player, printing all the players, print players rankings and finally closing all open database connections. Now such a class is not easy to create, maintain and update and as it is involved in doing so many different tasks, a programming design to avoid.

===========================

High Cohesion

A good application design is creating an application with high cohesive classes, which are targeted towards a specific specialized task and such class is easy not only easy to create, but also easy to maintain and update.

class PlayerDatabase

{

ConnectDatabase connectD= new connectDatabase();

PrintAllPlayersInfo allPlayer= new PrintAllPlayersInfo();

PrintRankings rankings = new PrintRankings();

CloseDatabase closeD= new CloseDatabase();

PrintSinglePlayerInfo singlePlayer = PrintSinglePlayerInfo();

}

class ConnectDatabase

{

//connecting to database.

}

class CloseDatabase

{

//closing the database connection.

}

class PrintRankings

{

//printing the players current rankings.

}

class PrintAllPlayersInfo

{

//printing all the players information.

}

class PrintSinglePlayerInfo

{

//printing a single player information.

}

Unlike the previous program where we had a single class performing many different tasks, here we have created several different classes, each class performing a specific specialized task, leading to an easy creation, maintenance and updating of these classes . Classes created by following this programming design are said to performing a cohesive role and are high cohesion classes, which is an appropriate programming design while creating an application.

=================================================================

Answer b

Program to find the sum of two number

// main class

public class Sum {

// main method

public static void main(String[] args) {

//variable declaration

int a,b,c=0;

// scanner class object to read the user input

Scanner sc=new Scanner(System.in);

// take the first user input

System.out.println("Enter the first number");

a=sc.nextInt();

// take the second user input

System.out.println("Enter the second number");

b=sc.nextInt();

// sum the number and store in c

c=a+b;

System.out.println("Sum of two number is = " +c);

}

}

Output

Program to find the difference between to number

// main class

public class Difference {

// main method

public static void main(String[] args) {

//variable declaration

int a,b,c=0;

// scanner class object to read the user input

Scanner sc=new Scanner(System.in);

// take the first user input

System.out.println("Enter the first number");

a=sc.nextInt();

// take the second user input

System.out.println("Enter the second number");

b=sc.nextInt();

// find the difference between and the number store in variable c

c=a-b;

System.out.println("Difference of two number is = " +c);

}

}

Output

Program to find the product of two number

// main class

public class Product {

// main method

public static void main(String[] args) {

//variable declaration

int a,b,c=0;

// scanner class object to read the user input

Scanner sc=new Scanner(System.in);

// take the first user input

System.out.println("Enter the first number");

a=sc.nextInt();

// take the second user input

System.out.println("Enter the second number");

b=sc.nextInt();

// find the Product of two number and store in variable c

c=a*b;

System.out.println("Product of two number is = " +c);

}

}

Output

==============================================================

Answer c

All access modifiers method

------------------------------------------------------------

Public Method

Any class, in any package, can call a class's public methods. To declare a public method, use the keyword public.

For example,

class PublicMethod {

public void methodPublic() {

System.out.println("i am public method");

}

}

-------------------------------------------------

Private Method

This private method is most restrictive they are inaccessible in other classes, in any package, private method is accessible only the class in which a it is defined can call that method. To declare a private method, use the keyword private

For example,

class Base {

private void foo() {}

}

class Derived extends Base {

public void foo() {}  

}

public class Main {

public static void main(String args[]) {

Base b = new Derived();

b.foo();

}

}

this program give a compilation error because private method of base can't accesible in Derived class

-----------------------------------------

Protected Method

The method which are declared with protected access modifier in a base class can be accessed only by the derived class or subclass in other package or any class within the package of the protected method is define. To declare a protected method, use the keyword protected

class Base {

protected void foo() {

}

}

class Derived extends Base {

public void foo() {

}  

}

public class Main {

public static void main(String args[]) {

Base b = new Derived();

b.foo();

}

}

this program does not give any compilation error because protected method of base is accesible in Derived class

---------------------------------------------------------

Static Method

If you apply static keyword with any method, it is known as static method.

A static method belongs to the class rather than the object of a class.

A static method can be invoked without the need for creating an instance of a class.

A static method can access static data member and can change the value of it.

//Java Program to get the cube of a given number using the static method  

  

class Calculate{  

static int cube(int x){  

return x*x*x;  

}  

  

public static void main(String args[]){  

int result=Calculate.cube(5);  

System.out.println(result);  

}  

}

Output:125

---------------------------------------------------------

Final Method

If you make any method as final, you cannot override this method in another class or subclass.

class Base {

final void foo() {

}

}

class Derived extends Base {

public void foo() {

}  

}

public class Main {

public static void main(String args[]) {

Base b = new Derived();

b.foo();

}

}

this program give a compilation error because final method of base can't override in Derived class

========================================================================================

Answer d

Exception

An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run time, that disrupts the normal flow of the program’s instructions. so the other of program is not expected that is why we need to handeled these exception.

There are two type of exception

1- Checked Exception or Compile Time Exception

2- Unchecked Exception or Runtime Exception

Checked Exception

A checked exception is an exception that occurs at the compile time, these are also called as compile time exceptions. These exceptions cannot simply be ignored at the time of compilation, the programmer should take care of (handle) these exceptions.

For example, if you use FileReader class in your program to read data from a file, if the file specified in its constructor doesn't exist, then a FileNotFoundException occurs, and the compiler prompts the programmer to handle the exception.

import java.io.File;

import java.io.FileReader;

public class FilenotFound_Demo {

public static void main(String args[]) {

File file = new File("E://file.txt");

FileReader fr = new FileReader(file);

}

}

They are many type

1-IO Exception

1.1 - EOF Exception

1.2- File Not Found Exception

2-SQL Exception

3-Interrupted Exception

==================================================

Unchecked or Runtime Exception - An unchecked exception is an exception that occurs at the time of execution. These are also called as Runtime Exceptions. These include programming bugs, such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation.

For example, if you have declared an array of size 5 in your program, and trying to call the 6th element of the array then an ArrayIndexOutOfBoundsExceptionexception occurs.

public class Unchecked_Demo {

public static void main(String args[]) {

int num[] = {1, 2, 3, 4};

System.out.println(num[5]);

}

}

There are many type of Unchecked Exception

1 - Arithmetic Exception

2 - Null Pointer Exception

3 - Class Cast Exception

4 - ArrayIndexOutOfBound Exception

So we required to handeled these exception we can handeled these exception by using following keyword

1- try

2- catch

3- finally

4- Throw

5- Throws

================================================================================

If you have any query please let me know first i will give resolution

Add a comment
Know the answer?
Add Answer to:
a]using appropriate programming examples differentiate between cohesion and coupling[10marks] b]Write a java program that requests a...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Programming Project 3 See Dropbox for due date Project Outcomes: Develop a Java program that uses:...

    Programming Project 3 See Dropbox for due date Project Outcomes: Develop a Java program that uses: Exception handling File Processing(text) Regular Expressions Prep Readings: Absolute Java, chapters 1 - 9 and Regular Expression in Java Project Overview: Create a Java program that allows a user to pick a cell phone and cell phone package and shows the cost. Inthis program the design is left up to the programmer however good object oriented design is required.    Project Requirements Develop a text...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT