Results for Class

Static and Non Static Inner Class in Java

January 10, 2019
Static and Non Static Inner Class in Java
Static and Non Static Inner Class in Java

Static and Non Static Inner Class in Java:

It is possible in java to put a class definition within another class definition. The enclosing class is called outer class and the class inside is called inner class.This technique allows us to group classes that logically belong together and to control the visibility of the one within other.The inner classes are different from Composition.
Inner classes can not be accessed directly until we have create an object for the outer class.
Inner classes can be classified as:

  1. Non Static Inner Class
  2. Static Inner Class
There are other inner classes as well. read here for more.

Non Static Inner Class:

The generic syntax for Non Static Inner class:


OuterClassName.InnerClassName <<Object/handle>>=OuterClassHandle.new innerClassName();
 

An example of Inner class:


public class Parcel{
       class Content{
       private int i=11;
       public int value(){return i;}
       }
       class Destination{
       private String address;
       Destination(String add){address=add;}
       String getAddress(return address;}
       }
public static void main(String args[])
{
Parcel p=new Parcel();
Parcel.Content c=p.new Content();
Parcel.Destination d=p.new Destination("India");
}
}
 
Here the class Destination and Content are hidden inside the Parcel Class. Parcel is the outer class and these two are hidden class.

Parcel p=new Parcel();
 
This code creates a handle for outer class and to create handle for inner class and to get the inner class we need to use:

Parcel.Content c=p.new Content();
 

We can not access the inner class by simply creating the outer class handle,we must use the instance of the outer class to create instances of inner class and then to access it.

Outer class may have method that returns a handle to an inner class:


public Content cont(){return new Content();}
//in that case we can define-
Parcel p=new Parcel();
Parcel.Content c=p.cont();
//for destination
public Destination dest(String s){
return new Destination(s);
}
Parcel.Destination d=p.dest("India");
 

Static Inner Class:

By static inner class, we do not need to create object of the outer class for creating object of the inner class.Instead we can call the methods or create object using the generic syntax given below:

Generic Syntax for static Inner Class:


OuterClassName.methodName();
 

An example of static Inner Class:


abstract class Content{
abstruct public int value();
}
interface Destination{
String getAddress();
}
public class Parcel{
private static class PContenet extends Content{
private ingt i=11;
public int value(){return i;}
}
protected static class PDestination implements Destination{
private String address;
private PDestination(String add)
{
address=add;
}
public String getAddress(){return address;}
}
public static Destination dest(String str)
{
return new PDestination(str);
}
public static Content con()
{
return new PContent();
}
public static void main(String args){
Content c=Parcel.con();
Destination d=Parcel.dest("India");
}
}
 

Static and Non Static Inner Class in Java Static and Non Static Inner Class in Java Reviewed by Animesh Chatterjee on January 10, 2019 Rating: 5

All About Class and Object in Java

October 22, 2018


Say we want to design a beautiful city. For that,we need to chalk out a plan for roads,houses,shops etc in a paper. Then we will design each of these individually,say a house. The blueprint of house will say how many doors will be there,how many windows,how many floors etc.Each of these houses will have its owner details when they are built and distributed.So in the sense the houses will look a like but the details of each houses like owner,how many occupants will be there in the house, will vary.Even the interior may vary from one house to another. But the base of creating a house will be same.This is same for roads,the design will be same but the name,locality and length will be different. It is similar to create a beautiful application using java. As a pure object oriented language,everything in Java should be inside a class.Java classes are the blueprint or master plan just like a master plan of a house.we can create any number of houses from this master plan. The master plan is called class and the individual houses created from this master plan is called object.

Again say our trainer has asked for a single pager resume. The trainer also has given a set of things in a document(Like -name,technology,experience,contact number ect).In real world this document is treated as template or blueprint and each individuals when created their own resume follow the same rules with different data. In this example,we can say the class is a template of the document and each document created from this template is called object.The objects will have their own set of data.

So in general the flow of the class and object creation is something like:
define a class-->create objects form the class--->send message to the objects

Aristotle was first to begin a study of the concept of type.He spoke about "the class of fishes and the class birds".The concept that all objects while being unique ,are also part of the set of objects that have characteristics and behaviors in common was directly used in the first object oriented language(Simula-67).Its fundamental keyword class that introduces a new type into a program(class and type are often used synonymous).
A class is actually describing "a class of objects".If we create a class of birds,any object belonging t this class will share these characteristics and behaviors.



A Class:
Classes provide a convenient method for packing together a group of logically related data items and functions that work with them.A class is given a name(called Identifier) to distinguish from other classes of the application.The class includes physical components called member elements and number of methods for operations. It is a datatype where the class creator will define how the new type of objects looks like.The linking and bonding between data and operations on these data is known as encapsulation.In the context of behavior, in approach, parameters to the behavior and return type should be primitive data type or a class object.

A class is an user defined data types with a template that provides the definition of the properties.Once the class type has been defined , we can create variables of that type using declaration that are similar to the basic type declarations that are similar to the basic type declaration. These variables are called instance of the class.(They are objects of that class)

The basic structure of the class is :

class className[extends superclass][implements someOtherclass]
{
[field declaration]
[methods declaration]
}
 
Filed declaration
Data encapsulated in a class by placing data fields inside the body of the class definition. These variables are called instance variables as they are created whenever an object of the class is instantiated. The declaration is exactly same as local variables.


class Rectangle{
int length;
int width;
}
 
Once they are declared , there is no space allocated to them.
Design of a class
While designing qualifier "-" signifies private and "+" signifies public.
like
-firstName=>String but private
+setFirstName(firstName)=> String but public

Collectively the variables and methods of a class are often referred to as members or fields of a class.
The transformation from a conceptual class diagram to class code is depicted here:
Class Diagram Class Code
MyClass -----------------------> public class MyClass
-firstName:String -----------------------> private firstName
+setFirstName(firstName:String) -----------------------> public  void setFirstName(String firstName)
{
this.firstName=firstName;
}
+getFirstName():String -----------------------> public String getFirstName()
{
return firstName;
}
so on....
the constructor is omitted here ,but in reality, we will have a constructor for a class.
Below is the general formula for a class:

<<Access specifier>> class className [extends SuperClass Name] implements interface1,interface2,....interfaceN{
//member elements mostly private
[Deceleration of member elements]
//methods mostly public
[Deceleration of methods]
}

Method declaration:
A class with only data fields has no life as there is no methods that operate on that data.The objects created by such class can not respond to any message.So it is necessary to design methods. Methods are declared inside the body of the class but immediately after the declaration of the instance variables.

[access modifier][specifier][return type]methodname(parameterList)
{
//method body
}
 
The four basic parts of the valid method are as follows:

  1. The name of the method(methodname)
  2. The return type of the method
  3. the list of parameters
  4. the body of the method.

We can pass object and some primitive data type to a method in the form of an argument and can return an object or primitive data type.
like setValue(int xyz);
anything inside the first bracket is considered as payload to the function.It is a mechanism by which we either pass value of data or reference to the object.Certainly a class have a function with empty payload .Like
setValue();

public class MyClass{
private String firstName();
public void setFirstName(String firstName)
{
this.firstName=firstName;
}
public String getFirstName(){
return firstName;
}
}
 
In the above statement, MyClass is an example of the structure of the class having one variable called firstName.If the constructor of the class MyClass() is called, the variable is set to the default value. In case, the constructor sets the value, it will be overridden.
Therefore every member variable will have a setter and a getter method so that the objects created from the class pass and change the values.
like setXXX(datatype value);//value passed
getXXX(){return datatype;}//method with no payload

The return type could be inbuilt data types or a class object.A method may not have any valid return value,in such case the return type will be void.The argument list is enclosed with parentheses.The list contains variables in a list separated by comma.A method may also take no input in such case the argument list is empty parentheses."()" .
like:
getValue();

Most of the times,when we use classes,we will have many methods and variables within the class.Instance variables and methods in classes are accessible by all methods in the class but a method can not access variables declared in other method.

class abc{
int x;
//legal
void method1()
{
x=10;
int y=x;
}

void method2()
{
int z;
x=5;
z=10;
//illegal as y is part of method1
y=1;


}
 

Data member of a class
Data member is thing we want to communicate via its handle.It can be of any type(primitive) which is not handle.It can be a handle to an object(it must be initialized to connect it to an actual object using new in constructor).If it is a primitive data type,we can initialize it directly at the point of definition in the class.
Guidelines for class creation:

  • By convention a class name starts with a capital letter.like PrintStream
  • class is a keyword and declares that a new class definition as follows.
  • class definition in Java starts with a opening braces("{")  and ends with a closing braces.("}").
  • class contains two types of elements-Data members called fields and member functions called methods.
  • Methods in java,can be created as a part if the Class.A method can only be called for an object.Except static methods can be called for the class without an object.
Java being a single rooted language,all classes are child of Object class.

public class MyClass{..}
//is equivalent to 
public class MyClass extends java.lang.Object{...}
 
Semantically java.lang.Object class is an abstract class but syntactically it is not declared as abstract.As it is a concrete class we can create object of the Object class.
so

Object o=new Object() //is legal but not sure where to use its methods
a.methods();
 
An Object:
Instance of a class is called object .An object in java essentially means a block of memory that contains space to store all the instance variables.Thus ,Object and instance are interchangeable in java.So creating an object is referred to as instantiation of an object. In object oriented programming language, Objects can communicate between themselves using message. They know which message is for which object and how to interact with it.Message is sent to object to perform some operation.Object is having data and behaviors. The linking and bonding between data and operations on these data is known as encapsulation.(so an object is an amalgam of data and code).These data can only manipulated using these operations.In other words,objects data values are not directly accessed from outside,instead they are accessed via the object's behaviors.So an object is having some private data values and public behaviors to manipulate the data.Calling a specific method in an object is referred as sending a message.Objects can be created using the new operator.The new operator creates an object of the specified class and return the reference of that object.
Construction of an Object

MyClass mc=new MyClass();
//or
MyClass mc;//declare the object
mc=new MyClass();//instantiate the object
 
where Myclass- is the provider class,
mc is the object reference of the MyClass,
new creates the instance of the provider class,
MyClass() is the constrcutor of the provider class.This is the default constructor or can be overloaded constructor.We can create n numbers of objects by using this syntax:

MyClass mc1=new MyClass();
MyClass mc2=new MyClass();
MyClass mc3=new MyClass();
.....
MyClass mcn=new MyClass();
 
Each object holds some amount of memory space and has its own copy of instance variables of its class.It also signify that any change to the variable of its one object have no effect on the variables of another.
We can create two or more references to the same object.

MyClass mc1=new MyClass();
MyClass mc2;
mc2=mc1;
 
The user class or object is only bothered as the methods exposed by the provider class.It does not know anything about the implementation of the method.So an object of a provider class implements the details of what a method does.Provider class only knows how the method is implemented.Now to call a method provide by the provider class, we need to use the dot operator to gain access to the provider class's field if they are public.
like

mc.setFirstName("Joghn");
//or
String name=mc.getFirstName();
 
All variables of an object must be assigned some value before they are used.From outside of the class we can not assign/access the variables directly as most of the cases they are private.To do this we need to account object and a dot (.) operator.

objectName.variableName=value;
objectName.methodName(paramlist)
 
if the instance variables are public then we can follow this approach:

class MyClass{
public int x;
public int y;

}
class Test{
MyClass mc1=new MyClass();
mc1.x=10;
mc1.y=15;
}
 
if the instance variables are private then we can follow this approach:

class MyClass{
private int x;
private int y;
//we can define an argumented constructor
public MyClass(int x,int y)
this.x=x;
this.y=y;
}
//or we can define some  getter or setter method
public void setValues(int x,int y)
this.x=x;
this.y=y;
}
class Test{
MyClass mc1=new MyClass(10,15);
//or 
MyClass mc1=new MyClass();
mc1.setValues(10,15);
}
 
for function with a payload or argument to understand the process better ,lets start from right to left. we pass an argument called Joghn(string) to the method setFirstName.And call this method on the instance of the provider class -MyClass using a .(dot) operator to identify the specific object (stored in the memory) for this method call. This is how we use an object of provider class.What happens internally:
once we created an object using new oiperator,the required arguments needs to be passed to the constructor.The JRE allocates sufficient memory to store fields of the object and initailizes its state.When initialization is done,the JRE returns a reference to the new object. So we can say the constructor returns an object reference to the object stored in memory.The default constructor takes no arguments and contains no code.It is provided automatically by the compiler if developer has not provided any constructor in the class.
But this is theoretical,how to execute the object?
Well we will execute the object of a provider class by inserting them a container class and use main method to trigger the execution.
Most Java applications may have any number of classes but they will surely have a single main that should trigger the execution.
An Example

public class MyContainerClass{
public static void main(String args[])
{
MyClass myObj=new MyClass();
myObj.setFirstName("Xavior");
}
}
 
In order to create an instance of class MyClass, We need to create an container class , then we can create the instance. The main is the starting function to kick of execution.


Guidelines for object creation:

  • An object by convention starts with a small letter like obj.
  • The object must be able to perform that method call.
Data member of an object
Each object keeps its own storage for its data members,the data members are not shared among objects.We may have any number of classes, but they will have no impact of our program until and unless we create an object from that class.

class Myclass{
int i;
float f;
boolean b;
}
//this class does not anything unless we create an object using new operator
Myclass mc=new Myclass();
 
We can assign values to the data members by the object name(handle) by a dot(.) operator
like-

mc.i=10;
mc.f=1.0f;
mc.b=false;
 
our object may also contain other objects which we would like to call a function like-
System.out.println("Hello Java");
It means that select out from class System and call println() method.
Scope of Objects
Java objects do not have the same lifetimes as primitives.When we create a java object using new,it hangs around past the end of the scope.

{
String myStr=new String("java");
}
//end of scope of myStr
 
The handle myStr vanishes at the end of the scope.However the string object myStr was pointing to,is still occupying memory.In the above code,there is no way to access the object because it is out of scope post this code line. Its turns out that because objects created with new operator stay around,as long as we want them.In Java it makes sure the objects are available when they are needed. Once objects created they fill up memory that halts the program.Java has a garbage collector ,which is a process running in the background(low priority execution and does not interfere program execution).The garbage collector looks at all the objects created by new and figures out which one's are not being referenced any further.Then it release the memory for those objects.This memory can be used by new objects.Thus a java coder never has to worry about reclaiming memory.This eliminates the problem of memory leakage where the programmer forgets to release memory.
Methods,arguments and return value:
Initially a function is termed as a named subroutine.Method is described as "a way to do something".Other way,methods in java determine the messages,an object can receive.the structure of the method is as follows:

returnType method Name(argumentList)
{
//method body
//return statement
}
 
returnType is the type of the value that pops out of the method after we call it. methodName is the meaningful name we can imagine and identifies the method. Argumentlist is the list of the type of argument and names for the information we want to pass to the method.If we try to call the wrong method for an object ,we will get a compile time error.The generic syntax for calling a method:
objectName(handle).(dot).methodName() with argument or without any argument.
If the class on whose handle we call the method (),has the method written,we will be able to perform the method call.
The return value must compatible with the return value defined in the method signature.
The call of the method is commonly referred as sending the message to the object.


All About Class and Object in Java All About Class and Object in Java Reviewed by Animesh Chatterjee on October 22, 2018 Rating: 5

Abstract Class Concept Simplified in Java

October 15, 2018
Abstract Class Concept In Java
Abstract Class Concept In Java

Abstract Class Concept Simplified in Java

A class is having a method definition but not implementation is called Abstract class. So if we derive one class from an abstract class we must provide implementation for every method defined in the abstract class.If we do not do it our new class is be treated as abstract class and we won't be able to create instance of that class.

The more we go towards class hierarchy,the more we create just the structure to create the sub classes. These are more rules than actual.so upwards the higher in hierarchy classes are more abstract classes.  When a class provides a common interface for all the classes derived from it,the class provides some dummy as well as original methods.Abstract classes are such classes in java which contains one or more abstract methods in it.

Here all threes classes inherits the shape class.The shape class is created to serve a common class. The shape class serves in our goal of achieving inheritance and polymorphism.But it was not built to be instantiated. Such class can be labelled as Abstract class.An abstract class exists only to express the common properties of all its sub classes so that they can be expressed differently for each different sub types.It establishes a basic form,so that we can say what is common with all the derived classes.
An abstract class is created when we want to manipulate a set of classes through this common interface.
Abstract Class
Abstract Class

Three classes Rectangle,Circle and Triangle have Display(),CalculateArea() these two common methods but they act differently as context changes. Here the abstract class Shape is the parent of these classes and has these methods. Each class by inheritance will get these methods and they need to implement as per their context.
An abstract class can be structured as

abstract class Shape{
...
...
}
So we can not perform the following operation for abstract class Shape.An abstract class is one that is not used to construct objects but only provides a base for making sub classes.If we do that compiler will throw an error message.

Shape obj=new Shape();
 
rather we have to do the following:
A class that is not abstract said to be concrete class .We can create objects belonging to a concrete class but not to an abstract class.

Rectangle objRect=new Rectangle();
Circle objCir=new Circle();
Triangle objTrian=new Triangle();
 
It is possible that we do not announce Shape class as abstract and we instantiate it. But in that case object will have no use in our code and may cause potential errors.In this example,Shape and Display() method are semantically abstract.we can redesign the class with an abstract modifier to tell java that Shape class is an abstract class.
abstract methods:
When final classes can not be sub classed and final methods can not be redefined,java allows opposite to that by using abstract keyword. This indicates that a method must always be redefined in a subclass thus making overriding compulsory. 
An abstract method is an incomplete method that has just the method definition but does not contain implementation. It is kind of dummy method.In this context,Display(),CalculateArea() methods are dummy methods.
signature will be:

abstract public void CalculateArea();//no definition only declaration
abstract public void Display();//no definition only declaration
 
Now these two methods for the above three classes()[Rectangle,Circle,Triangle] are different and have to be overridden in the respective classes. These methods does not have meaning in the Shape class.But we need to make sure that all the inheriting classes do have the method.Such methods can be labeled as abstract methods.So for a abstract class there is no need of implementation of the abstract methods.It is only the signature.If we have an abstract class,objects of this class almost always have no meaning,hence we need to prevent the users from doing so.Either can print an error message,but that delays the information till runtime and not reliable. The best solution of this problem is to make them abstract method.

Things to remember for abstract class:


  1. An abstract class may also have a complete method.
  2. A class can be declared as abstract even if it does not contain any abstract method.(during design)
  3. Reference of an abstract class can point to objects of it's sub classes there by achieving the run time polymorphism.Exaple- Shape obj=new Rectangle();
  4. A class must be declared abstract if it has one or more abstract methods.
  5. A variable whose type is given by an abstract class can only refer to objects that belong to concrete sub class of the abstract class.
  6. An abstract class is not a concrete class ,we can not use extends keyword while deriving new classes from it. 
  7. If we inherit a class from an abstract class and we want to make objects of the new type,we must provide method definitions of all the abstract methods,in the base class. If we don't(we have an option here),then the derived class is also become an abstract class.
  8. All derived class methods that match the signature of the base class declaration will be called using the dynamic binding mechanism.If the method's name is the same as the base class but the argument are different then we will get overloading.
  9. We can not declare abstract constructor or abstract static methods.

Structure of the abstract Shape class


abstract class Shape{
abstract public void CalculateArea();
abstract public void Display();
}
 
Any subclasses of this needs to implement the abstract class

class Rectangle implements Shape{
//provide implementation of the methods of shape
Display(){}
CalculateArea(){}
}
 
Abstract Class Concept Simplified in Java Abstract Class Concept Simplified in Java Reviewed by Animesh Chatterjee on October 15, 2018 Rating: 5

All About Class Class in Java

September 06, 2018
This is a very interesting Class called Class in java. Instance of the Class Class only represents classes and interfaces in the java applications. There are no member elements and public constructors available for Class Class. Class objects are constructed automatically by JVM when Classes are loaded into JVM and by the help of the method defineClass()[it stays in ClassLoader Class]
Below is the structure of Class -Class

public final Class java.lang.Class extends java.lang.Object
{
//methods
public static Class forName(String ClassName);
public ClassLoader getClassLoader();
public Class[] getInterfaces();
public Class getSuperClass();
public String getName();
public boolean isInterface();
public Object newInstance();
public String toString();
}
 
All About Class Class in Java All About Class Class in Java Reviewed by Animesh Chatterjee on September 06, 2018 Rating: 5
Powered by Blogger.