Advertisement
//Java - Example of tight coupling
class A
{
public String name; //public data member of A class
public String getName()
{
if(name!=null) //Checking a valid access of instance variable, "name"
return name;
else
return "not initiaized";
}
public void setName(String s)
{
if (s==null) //Checking a valid setting of instance variable, "name"
System.out.println("You can't initialized name to a null");
else
name = s;
}
}
class B
{
public static void main(String... ar)
{
//Creating an object of class A
A ob = new A();
//Directly setting the value of data member "name" of class A, due to tight coupling between the class A and B
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);
}
}
Name is null
Advertisement
//Java - Example of loose coupling
class A
{
private String name; //data member "name" is declared private to implement loose coupling.
public String getName()
{
if(name!=null) //Checking a valid access to data member, name
return name;
else
return "not initiaized";
}
public void setName(String s)
{
if (s==null) //Checking a valid setting of data member, name
System.out.println("You can't initialize name to a null");
else
name = s;
}
}
class B
{
public static void main(String... ar)
{
//Creating an object of class AA
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());
}
}
You can't initialized name to a null
Name is not initiaized
//Java - Example of a low cohesion class
class PlayerDatabase
{
public void connectDatabase();
public void printAllPlayersInfo();
public void printSinglePlayerInfo();
public void printRankings();
public void printEvents();
public void closeDatabase();
}
//Java - Example of high cohesion classes
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.
}
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement