Creating object(s) for class,interface,Abstract class,final class and enum in JAVA.

In java every communication among the classes merely done by the methods with the help of objects.The below link shows the various advantages with object in java.

Advantages with Object:

  • Define the structure and behavior of a class.
  • Independence-i.e One object values doesn’t affects the other object values.
  • Modularity- Once it got created ,We can move the object over methods or any where in the program.

Bundling code into individual software objects provides a number of benefits, including:

  1. Modularity: The source code for an object can be written and maintained independently of the source code for other objects. Once created, an object can be easily passed around inside the system.
  2. Information-hiding: By interacting only with an object’s methods, the details of its internal implementation remain hidden from the outside world.
  3. Code re-use: If an object already exists (perhaps written by another software developer), you can use that object in your program. This allows specialists to implement/test/debug complex, task-specific objects, which you can then trust to run in your own code.
  4. Pluggability and debugging ease: If a particular object turns out to be problematic, you can simply remove it from your application and plug in a different object as its replacement. This is analogous to fixing mechanical problems in the real world. If a bolt breaks, you replace it, not the entire machine.

WHY WE NEED OBJECT IN JAVA….? 

Creating a object for Class:

  • There are numerous ways to create an object for a particular class in java.But here i am showing only the most generalized way i.e using new keyword.

class Demo{
public String string;
//Definfing the structure of class
public Demo(String str){
this.string=str;
System.out.println(“In construcor”+string);
}
//Here we are changing the behabiour of class through method
public String getName(){
return “Brad Pitt”;
}
}
public class Demo_Object{
public static void main(String[] args)throws Exception{
//creating the object with new() operator
Demo demoObject=new Demo(” Mr..”);
String str=demoObject.getName();
System.out.println(str);
}
}

o/p:
D:\OCJP>javac Demo_Object.java

D:\OCJP>java Demo_Object
In construcor Mr..
Brad Pitt

 

Creating Object for an interface:

As all of us knew that interface is a kind of class but the only difference we see is abstraction i.e interface is 100% abstract.Directly we can’t create object for interface.Why so,Here are nice explanations

https://www.quora.com/Why-cant-we-create-an-object-to-interface-in-Java

http://softwareengineering.stackexchange.com/questions/263301/i-want-to-understand-clearly-why-cant-we-instantiate-an-object-of-an-abstract-c

But through Anonymous classes we can create the objects.Example programs are below.

interface TestInterface{
String toString();
}

public class Object_Creation3{
public static void main(String[] args)throws Exception{
System.out.println(new TestInterface(){
public String toString(){
return “HAAAAAAAAAAAhhhaaaaaaa”+this.getClass();
}
});
}
}

o/p:

D:\OCJP>javac Object_Creation3.java

D:\OCJP>java Object_Creation3
HAAAAAAAAAAAhhhaaaaaaaclass Object_Creation3$1

 

With that syntax, you create an anonymous class, which is perfectly legal.

Internally, anonymous classes are compiled to a class of their own, called EnclosingClass$n where the enclosing class’ name precedes the $ sign. and n increases for each additional anonymous class. This means that the following class is being created:

 

Object Creation for Abstract class:

We can’t create for object for an Abstract class because if we do also the implementation must happen i.e through extends otherwise it will left remains as an empty template.

Because it’s abstract and an object is concrete. An abstract class is sort of like a template, or an empty/partially empty structure, you have to extend it and build on it before you can use it.

Take for example an “Animal” abstract class. There’s no such thing as a “pure” animal – there are specific types of animals. So you can instantiate Dog and Cat and Turtle, but you shouldn’t be able to instantiate plain Animal – that’s just a basic template. And there’s certain functionality that all animals share, such as “makeSound()", but that can’t be defined on the base Animal level. So if you could create an Animal object and you would call makeSound(), how would the object know which sound to make?

 

abstract class AbstractClassSample{
public String name;
//public AbstractClassSample(String name){
//this.name=name;
//}
public abstract void getName();
public String getCompany(){
return “OpenText”;
}
}

public class Abstract_ObjectCreation{
public static void main(String[] args)throws Exception{
AbstractClassSample abstractClassSample=new AbstractClassSample(“Sundar pichai”);
System.out.println(abstractClassSample.getCompany());
}
}

o/p:

D:\OCJP>javac Abstract_ObjectCreation.java
Abstract_ObjectCreation.java:14: error: AbstractClassSample is abstract; cannot
be instantiated
AbstractClassSample abstractClassSample=new AbstractClassSample(“Sundar picha
i”);
^
1 error

But we can get benefit with inheritance in the case of Abstract class by extending the abstract class to sub class and creating object for sub class as below.

abstract class AbstractClassSample{
public String designation=”Software Engineer”;
public AbstractClassSample(String d){
this.designation=d;
}
public abstract String getName();
public String getCompany(){
return “OpenText”;
}
}

class Abstract_Inheritence extends AbstractClassSample{
public int employeeId;
public Abstract_Inheritence(int no,String d){
super(d);
this.employeeId=no;
}
public String getName(){
return “Madhu”;
}
//public String getCompany(){
// return “PegaSystems”;
// }
}

public class Test_Inhiritence{
public static void main(String[] args)throws Exception{
Abstract_Inheritence abstract_Inheritence=new Abstract_Inheritence(123,”Associate”);
String s1=abstract_Inheritence.getName();
String s2=abstract_Inheritence.getCompany();
System.out.println(s1);
System.out.println(s2);
}
}

o/p:

D:\OCJP>javac Test_Inhiritence.java

D:\OCJP>java Test_Inhiritence
Madhu
OpenText

 

 

Object Creation for final class:

We can create object for a final class as normal i.e first use case.

final class Final_Demo{
public Final_Demo(String a){
System.out.println(“In Constructor”+a);
}
}

public class FinalClassObject{
public static void main(String[] args)throws Exception{
Final_Demo finalDemo=new Final_Demo(“Mr.Ramanjan”);
}
}

o/p:
D:\OCJP>javac FinalClassObject.java

D:\OCJP>java FinalClassObject
In ConstructorMr.Ramanjan

But final class cannot be extended .It will throgh the error as below.

final class Final_Demo{
public Final_Demo(String a){
System.out.println(“In Constructor”+a);
}
}

public class FinalClassObject extends Final_Demo{
public static void main(String[] args)throws Exception{
Final_Demo finalDemo=new Final_Demo(“Mr.Ramanjan”);
System.out.println(“errorr……”);
}
}

o/p:

D:\OCJP>javac FinalClassObject.java
FinalClassObject.java:7: error: cannot inherit from final Final_Demo
public class FinalClassObject extends Final_Demo{
^
FinalClassObject.java:7: error: constructor Final_Demo in class Final_Demo canno
t be applied to given types;
public class FinalClassObject extends Final_Demo{
^
required: String
found: no arguments
reason: actual and formal argument lists differ in length
2 errors

Creating Object for enum:

Enums cannot be intialized as they only a private constructor.

public enum Sample{
   READ,WRITE
}   


//Will get convetred the above code into below internally.


class Sample extends Enum {
    public static final Sample READ = new Sample("READ", 0);
    public static final Sample WRITE = new Sample("WRITE", 1);

    private Sample(String s, int i)
    {
        super(s, i);
    }

    // More methods, e.g. getter
}
Advertisements

Is Java is case-sensitive language?

YES…yes

Look at below snippet.

public class Main_Demo{
public static void main(String[] args)throws Exception{
System.out.println(“Keep Challenging………….”);
System.out.println(“Building tomorrow’s enterprise………….”);
String name=”cognizant”;
String NAME=”Infosys”;
System.out.println(name);
System.out.println(NAME);
}
}

 

D:\OCJP>javac Main_Demo.java

D:\OCJP>java Main_Demo
Keep Challenging………….
Building tomorrow’s enterprise………….
cognizant
Infosys

D:\OCJP>

Though both having same name as name because of the feature of case sensitiveness. It takes as two different strings.

Even if i compile with case it won’t work.

D:\OCJP>javac Main_Demo.java

D:\OCJP>java MAIN_DEMO
Error: Could not find or load main class MAIN_DEMO

D:\OCJP>java main_demo
Error: Could not find or load main class main_demo

D:\OCJP>Main_Demo
‘Main_Demo’ is not recognized as an internal or external command,
operable program or batch file.

D:\OCJP>java Main_Demo
Keep Challenging………….

Case sensitive  and case- insensitive Languages:

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

Some computer languages are case-sensitive for their identifiers (C, C++, Java, C#, Verilog,[1] Ruby[2] and XML). Others are case-insensitive (i.e., not case-sensitive), such as Ada, most BASICs (an exception being BBC BASIC), Fortran, SQL[3] and Pascal.

 

 

Identifiers in JAVA

  • All the java components like  classes,interfaces,methods,variables,packages etc needs names in order to make benefit from them in our program .These names are called “identifiers”.
  • They are used to refer the actual reference value assigned to any variable etc.
  • Example:

 If i declare
String name=”India”;
int value=10;

Here name is a identifier of a class called java.lang.String;
Here value is an identifier which represents a primitive data type of int .It is having 10 as it’s value.

  • In the HelloWorld program, HelloWorld,String- HelloWorld, args, main and println are respresents methods. 

 

Legal Identifiers:

The set of rules of the compiler to determine whether a name is legal or not.Legal identifiers are must be composed of following combinations.They are

  • Numbers(0-9)
  • Currency Symbols($ as JAVA supports)
  • Connecting Characters(_)
  • Unicode characters(A_Z ,a-z,$,_)

Example:

public class Identifiers{
public static void main(String[] args)throws Exception{
int _a=10;
int _________abc_bc=10;
int abc_____455_dfj=10;
int a#=10;
int a$=10;
int $res=10;
int &iop=10;
int 34_u=10;
int char=10;
System.out.println(_a);
System.out.println(_________abc_bc);
System.out.println(abc_____455_dfj);
System.out.println(a#);
System.out.println(a$);
System.out.println($res);
System.out.println(&iop);
System.out.println(34_u);
System.out.println(char);
}

output:

D:\OCJP>javac Identifiers_Test.java
Identifiers_Test.java:6: error: illegal character: ‘#’
int a#=10;
^
Identifiers_Test.java:9: error: not a statement
int &iop=10;
^
Identifiers_Test.java:9: error: ‘;’ expected
int &iop=10;
^
Identifiers_Test.java:10: error: illegal underscore
int 34_u=10;
^
Identifiers_Test.java:10: error: not a statement
int 34_u=10;
^
Identifiers_Test.java:11: error: not a statement
int char=10;
^
Identifiers_Test.java:11: error: ‘;’ expected
int char=10;
^
Identifiers_Test.java:11: error: not a statement
int char=10;
^
Identifiers_Test.java:11: error: ‘;’ expected
int char=10;
^
Identifiers_Test.java:15: error: illegal character: ‘#’
System.out.println(a#);
^
Identifiers_Test.java:15: error: illegal start of expression
System.out.println(a#);
^
Identifiers_Test.java:18: error: illegal start of expression
System.out.println(&iop);
^
Identifiers_Test.java:19: error: illegal underscore
System.out.println(34_u);
^
Identifiers_Test.java:19: error: ‘)’ expected
System.out.println(34_u);
^
Identifiers_Test.java:19: error: illegal start of expression
System.out.println(34_u);
^
Identifiers_Test.java:20: error: ‘.class’ expected
System.out.println(char);
^
Identifiers_Test.java:21: error: reached end of file while parsing
}
^
17 errors

so by above program we came to know that we should fallow some rules in order to make it as an identifier.

Rules of Legal Identifiers:

  • It shouldn’t start with digit(0-9).
  • It shouldn’t  start with special charactes like (@ # %^&*()!)
  • It shouldn’t contain the keyword i.e “char” “int”
  • It can have prefered length. “ppppppp______dfds_dsgfdg”.
  •  It shouldn’t contain white spaces.
  • _ can be first letter.$ can be used in midddle.Apart from no special charactes are allowd.

Now i have removed all the invalid identifier declarations .It is working fine as expected.

public class Identifiers_Test{
public static void main(String[] args)throws Exception{
int _a=10;
int _________abc_bc=10;
int abc_____455_dfj=10;
int a_=10;
int a$=10;
//int a#=10;
//int $res=10;
//int &iop=10;
//int 34_u=10;
//int char=10;
System.out.println(_a);
System.out.println(_________abc_bc);
System.out.println(abc_____455_dfj);
//System.out.println(a#);
System.out.println(a$);
System.out.println(a_);
//System.out.println(a#);
//System.out.println($res);
//System.out.println(&iop);
//System.out.println(34_u);
//System.out.println(char);
}
}

output:

D:\OCJP>javac Identifiers_Test.java

D:\OCJP>java Identifiers_Test
10
10
10
10
10

D:\OCJP>

 

Why we should follow identifier rules:

  • Conflicts like int a-=10; If we declare like this compile got confused to choose whether it is a short hand operator or identifier.

Could usage:

Could can be used in several situations.Some of them are 

Possibility : 

  • Heavy rains could cause the road damage.
  • Heavy consumption of cigarette could cause  cancer.
  • Why did you do that? It could have broken your legs.
  • You could have called me first.
  • Due to hectic schedule,I couldn’t make it happen.

Ability:

  • I could play football when I was 18 years old.
  • Yesterday,I couldn’t eat full meal .

Suggestions:

  • You could have spent your time in new York.
  • We could take a auto because it’s too far.
  • We could go to a movie if all are interested.
  • You could have taken Cappuccino .

Request:

  • Could I have something to drink?
  • Couldn’t you help me with this for just  a minute?
  • Couldn’t he thinks about you?
  • Could you please help me out?

Permission:

  • Could I take this Friday off?
  • Could I take your pencil?
  • Could I use your laptop for sometime?
  • Could I take advantage over her?

It also used to tell something that has no possibility .

Janvir couldn’t have seen him .