Friday, September 9, 2016

Classes In Java

·         Abstract Class
1.       Similar to Interface except method can have body
2.       Can’t be instantiated but it can have constructors. The purpose is to initialize final variables from subclass (lazy initialization)
3.       abstract keyword used to create abstract method
4.       Subclass should implement all abstract method unless subclass is also abstract
5.   Can have constructor. 
public abstract class A{
private String s;
public void method1(){s=’Sample’};
public abstract void method2();
}

public class B extends A{
private String str;
public void method2(){str=’Subclass’};
}

·         Wrapper Class
1.       All wrapper classes in Java are immutable and final
2.       Primitive<-> Wrapper (byte<->Byte, short<->Short, int<->Integer, long<->Long, float <->Float, double <-> Double, char <-> Character, Boolean <-> Boolean)
3.       Primitive types can’t be null but wrapper classes can be. int=null Int=Null

Nested classes are of Two Types of nested classes
 Java Static Class
 Java Inner Class

·                                       Static Class:
1.       static class Test{} : wrong compilation error will come.
2.       Java doesn’t allow top level static class
3.       Java supports nested classes which can be static
4.       static nested class can access only static members of outer class
5.       3 class files are created. OuterClass.class; StaticNestedClass.class. Static class file is created as OuterClass$StaticNestedClass.class
6.       The only possible benefit is encapsulation
public class OuterClass(){
                private static String st=’str’;
                static class StaticNestedClass(){
                                private int a;
                                public int getA(){};
                                public String getSt(){return st};
                }
}

public class Test(){
                public static void main(String[] args){
                                OuterClass.StaticNestedClass snc=new OuterClass.StaticNestedClass();
                                System.out.println(snc.getST()); --- accessing static member of outer class
                }
}

·         Java Inner Class:
1.       Inner class is defined inside body of a class
2.       Can be private, public, protected, or with default access whereas outer class can have only public or default access
3.       Any non-static inner class
4.       Associated with the object of that class and can access all variables and methods of that class
5.       Can’t have any static variable in these
OuterClass outerObj=new OuterClass();
OuterClass.InnerClass innerObj=outerObj.new InnerClass();

No comments:

Post a Comment