#MasteryTopic

--Originally published at Jsph's Blog

Let’s get start with the masteries guys!

What is an…?

Object: Objects are key to understanding object-oriented technology. They consist of state and related behavior. An object stores its state in fields (variables in some programming languages) and exposes its behavior through methods (functions in some programming languages). Methods operate on an object’s internal state and serve as the primary mechanism for object-to-object communication. Hiding internal state and requiring all interaction to be performed through an object’s methods is known as data encapsulation — a fundamental principle of object-oriented programming.

#MasteryTopic

Attribute: An attribute is another term for a field. It’s typically a public constant or a public variable that can be accessed directly. In this particular case, the array in Java is actually an object and you are accessing the public constant value that represents the length of the array. The Attributes class maps Manifest attribute names to associated string values. Valid attribute names are case-insensitive, are restricted to the ASCII characters in the set [0-9a-zA-Z_-], and cannot exceed 70 characters in length. Attribute values can contain any characters and will be UTF8-encoded when written to the output stream.

#MasteryTopic

Method: A Java method is a collection of statements that are grouped together to perform an operation. When you call the System.out.println() method, for example, the system actually executes several statements in order to display a message on the console.

#MasteryTopic

 

Sources:

https://docs.oracle.com/javase/tutorial/java/concepts/object.html

http://www.tutorialspoint.com/java/java_object_classes.htm

http://stackoverflow.com/questions/8479038/what-is-attribute-in-java

http://www.tutorialspoint.com/java/java_methods.htm

http://mathbits.com/MathBits/Java/Methods/Lesson1.htm


#MasteryTopic

What are visibility modifiers, their purpose and use in practice?

--Originally published at TC201 Winter 2016 Jorge

Java provides a number of access modifiers to set access levels for classes, variables, methods and constructors. The four access levels are:

 

  • Visible to the package. the default. No modifiers are needed.

  • Visible to the class only (private).

  • Visible to the world (public).

  • Visible to the package and all subclasses (protected).

Default access modifier means we do not explicitly declare an access modifier for a class, field, method, etc.

 

A variable or method declared without any access control modifier is available to any other class in the same package. The fields in an interface are implicitly public static final and the methods in an interface are by default public.

 

Example:

 

Variables and methods can be declared without any modifiers, as in the following examples:

String version = "1.5.1";

boolean processOrder() {
   return true;
}

Private Access Modifier - private:

Methods, Variables and Constructors that are declared private can only be accessed within the declared class itself.

Private access modifier is the most restrictive access level. Class and interfaces cannot be private.

Variables that are declared private can be accessed outside the class if public getter methods are present in the class.

Using the private modifier is the main way that an object encapsulates itself and hide data from the outside world.

Example:

The following class uses private access control:

public class Logger {
   private String format;
   public String getFormat() {
      return this.format;
   }
   public void setFormat(String format) {
      this.format = format;
   }
}

Here, the format variable of the Logger class is private, so there's no way for other classes to retrieve or set its value directly.

So to make this variable available to the outside world, we defined two public methods: getFormat(), which returns the value of format, and setFormat(String), which sets its value.

Public Access Modifier - public:

A class, method, constructor, interface etc declared public can be accessed from any other class. Therefore fields, methods, blocks declared inside a public class can be accessed from any class belonging to the Java Universe.

However if the public class we are trying to access is in a different package, then the public class still need to be imported.

Because of class inheritance, all public methods and variables of a class are inherited by its subclasses.

Example:

The following function uses public access control:

public static void main(String[] arguments) {
   // ...
}

The main() method of an application has to be public. Otherwise, it could not be called by a Java interpreter (such as java) to run the class.

Protected Access Modifier - protected:

Variables, methods and constructors which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class.

The protected access modifier cannot be applied to class and interfaces. Methods, fields can be declared protected, however methods and fields in a interface cannot be declared protected.

Protected access gives the subclass a chance to use the helper method or variable, while preventing a nonrelated class from trying to use it.

Example:

The following parent class uses protected access control, to allow its child class override openSpeaker() method:

class AudioPlayer {
   protected boolean openSpeaker(Speaker sp) {
      // implementation details
   }
}

class StreamingAudioPlayer {
   boolean openSpeaker(Speaker sp) {
      // implementation details
   }
}

Here, if we define openSpeaker() method as private, then it would not be accessible from any other class other than AudioPlayer. If we define it as public, then it would become accessible to all the outside world. But our intension is to expose this method to its subclass only, thats why we used protected modifier.

If you still find it hard to understand what  the visibility modifiers in Java are, here are a couple of images that might help you

What are visibility modifiers, their purpose and use in practice?    What are visibility modifiers, their purpose and use in practice?

For more info I'll leave some of the links that helped me understand this concepts.

http://www.tutorialspoint.com/java/java_access_modifiers.htm

http://stackoverflow.com/questions/215497/difference-between-public-default-protected-and-private

 
 

 

What are”has-a” and “is-a” relationships?

--Originally published at TC201 Winter 2016 Jorge

IS-A relationship:

In object oriented programming, the concept of IS-A is a totally based on Inheritance, which can be of two types Class Inheritance or Interface Inheritance. It is just like saying "A is a B type of thing". For example, Apple is a Fruit, Car is a Vehicle etc. Inheritance is uni-directional. For example House is a Building. But Building is not a House.

 

It is key point to note that you can easily identify the IS-A relationship. Wherever you see an extends keyword or implements keyword in a class declaration, then this class is said to have IS-A relationship.

HAS-A relationship:

Composition(HAS-A) simply mean use of instance variables that are references to other objects. For example: Maruti has Engine, or House has Bathroom.

Let’s understand these concepts with example of Car class.

What are”has-a” and “is-a” relationships?

class Car {  
  
    // Methods implementation and class/Instance members  
  
    private String color;  
  
    private int maxSpeed;   
  
          
  
    public void carInfo(){  
  
        System.out.println("Car Color= "+color + " Max Speed= " + maxSpeed);  
  
    }  
  
  
  
    public void setColor(String color) {  
  
        this.color = color;  
  
    }  
  
  
  
    public void setMaxSpeed(int maxSpeed) {  
  
        this.maxSpeed = maxSpeed;  
  
    }  
 

As shown above Car class has couple of instance variable and few methods. Maruti is specific type of Car which extends Car class means Maruti IS-A Car.

class Maruti extends Car{  
  
    //Maruti extends Car and thus inherits all methods from Car (except final and static)  
  
    //Maruti can also define all its specific functionality  
  
    public void MarutiStartDemo(){  
  
        Engine MarutiEngine = new Engine();  
  
        MarutiEngine.start();  
  
        }   

Maruti class uses Engine object’s start() method via composition. We can say that Maruti class HAS-A Engine.

public class Engine {  
  
  
  
    public void start(){  
  
        System.out.println("Engine Started:");  
  
    }  
  
      
  
    public void stop(){  
  
        System.out.println("Engine Stopped:");  
  
    }  
  

RelationsDemo class is making object of Maruti class and initialized it. Though Maruti class does not have setColor(), setMaxSpeed() and carInfo() methods still we can use it due to IS-A relationship of Maruti class with Car class.

public class RelationsDemo {  
  
      
  
    public static void main(String[] args) {          
  
        Maruti myMaruti = new Maruti();  
  
        myMaruti.setColor("RED");  
  
        myMaruti.setMaxSpeed(180);  
  
        myMaruti.carInfo();  
  
          
  
        myMaruti.MarutiStartDemo();  
  
    }  
  
  
  

 

If we run RelationsDemo class we can see output like below.

Car Color = RED Max Speed  = 180

Engine Started:

If you still find it hard to understand what IS-A an HAS-A relationships in OO languages mean, here are a couple of images that might help you

 

What are”has-a” and “is-a” relationships?What are”has-a” and “is-a” relationships?

For more info I'll leave some of the links that helped me understand this concepts.

http://www.w3resource.com/java-tutorial/inheritance-composition-relationship.php

https://www.youtube.com/watch?v=uMwfqmVJ1Vw

What is delegation?

--Originally published at TC201 Winter 2016 Jorge

The delegation pattern is a design pattern in object-oriented programming where an object, instead of performing one of its stated tasks, delegates that task to an associated helper object. There is an Inversion of Responsibility in which a helper object, known as a delegate, is given the responsibility to execute a task for the delegator. The delegation pattern is one of the fundamental abstraction patterns that underlie other software patterns such as composition (also referred to as aggregation), mixins and apsects.

In this example, the Printer class has a print method. This print method, rather than performing the print itself, delegates to class RealPrinter. To the outside world it appears that the Printer class is doing the print, but the RealPrinter class is the one actually doing the work.

 

Delegation is simply passing a duty off to someone/something else. Here is a simple example:

class RealPrinter {	// the "delegate"
	void print() { 
		System.out.println("Hello world!"); 
	}
 }

 class Printer {	// the "delegator"
	RealPrinter p = new RealPrinter();	// create the delegate 
	void print() {
		p.print(); // calls the delegate
	}
 }
  
 public class Main {
	public static void main(String[] arguments) {
                // to the outside world it looks like Printer actually prints.
		Printer printer = new Printer();
		printer.print();
	}
 }

If you still find it hard to understand what delegation in OO languages mean, here are a couple of images that might help you

What is delegation?What is delegation?

For more info I'll leave some of the links that helped me understand this concept.

https://en.wikipedia.org/wiki/Delegation_pattern

http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/delegation.html

 

 

What is encapsulation?

--Originally published at TC201 Winter 2016 Jorge

Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance, polymorphism, and abstraction.

 Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as as single unit. In encapsulation the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class, therefore it is also known as data hiding.

 To achieve encapsulation in Java:

 

  • Declare the variables of a class as private.

  • Provide public setter and getter methods to modify and view the variables values.

 

Here's an example that demonstrates how to achieve Encapsulation in Java:

public class EncapTest{

   private String name;
   private String idNum;
   private int age;

   public int getAge(){
      return age;
   }

   public String getName(){
      return name;
   }

   public String getIdNum(){
      return idNum;
   }

   public void setAge( int newAge){
      age = newAge;
   }

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

   public void setIdNum( String newId){
      idNum = newId;
   }
}

The public setXXX() and getXXX() methods are the access points of the instance variables of the EncapTest class. Normally, these methods are referred as getters and setters. Therefore any class that wants to access the variables should access them through these getters and setters.

The variables of the EncapTest class can be accessed as below:

public class RunEncap{

   public static void main(String args[]){
      EncapTest encap = new EncapTest();
      encap.setName("James");
      encap.setAge(20);
      encap.setIdNum("12343ms");

      System.out.print("Name : " + encap.getName() + " Age : " + encap.getAge());
    }
}

Benefits of Encapsulation:

1. The fields of a class can be made read-only or write-only.

2. A class can have total control over what is stored in its fields.

3. The users of a class do not know how the class stores its data. A class can change the data type of a field    and users of the class do not need to change any of their code.

If you still find it hard to understand what encapsulation in OO languages mean, here are a couple of images that might help you

What is encapsulation?What is encapsulation?

For more info I'll leave some of the links that helped me understand this concept.

http://www.tutorialspoint.com/java/java_encapsulation.htm

http://javarevisited.blogspot.mx/2012/03/what-is-encapsulation-in-java-and-oops.html

https://www.youtube.com/watch?v=szYzBC89CPE

 

What is abstraction?

--Originally published at TC201 Winter 2016 Jorge

A class that is declared with abstract keyword, is known as abstract class in java. It can have abstract and non-abstract methods (method with body).

 

Before learning java abstract class, let's understand the abstraction in java first.

Abstraction is a process of hiding the implementation details and showing only functionality to the user.

 

Another way, it shows only important things to the user and hides the internal details for example sending sms, you just type the text and send the message. You don't know the internal processing about the message delivery.

 

Abstraction lets you focus on what the object does instead of how it does it.

Abstract class in Java:

A class that is declared as abstract is known as abstract class. It needs to be extended and its method implemented. It cannot be instantiated.

Example: abstract class A{} 

Abstract method in Java:

A method that is declared as abstract and does not have implementation is known as abstract method.

Example: abstract void printStatus(); //no body and abstract 

Example of an abstract class that has an abstract method:

abstract class Bike{ 

 abstract void run();

class Honda4 extends Bike{ 

void run();

System.out.println("running safely..");

public static void main(String args[]){  
 Bike obj = new Honda4();  
 obj.run();  
}  

If you still find it hard to understand what abstraction in OO languages mean, here are a couple of images that might help you

What is abstraction?What is abstraction?

For more info I'll leave some of the links that helped me understand this concept.

https://www.youtube.com/watch?v=TyPNvt6Zg8c

http://www.javatpoint.com/abstract-class-in-java

http://stackoverflow.com/questions/11965929/abstraction-vs-encapsulation-in-java