25
Closer look at classes Overloading Methods Overloading Constructor Objects as parameter to methods Objects as parameter to constructor Returning Objects Recursion String Class String Buffer Class Command line arguments Access Controle Static Keyword Usage Final Keyword Usage

Closer look at classes

Embed Size (px)

Citation preview

Closer look at classes

Overloading MethodsOverloading Constructor

Objects as parameter to methodsObjects as parameter to constructor

Returning ObjectsRecursion

String ClassString Buffer Class

Command line argumentsAccess Controle

Static Keyword UsageFinal Keyword Usage

Overloading methods• Overloading is ability of one function to perform different tasks.

• it allows creating several methods with the same name which differ from each other in the type of the input and the output

class Demo_class

{ /* having same method name*/

void demo()

{ System.out.println("hello world"); }

void demo(int a)

{ System.out.println("the value of a::"+a); }

public static void main(String[] y)

{ Demo_class d=new Demo_class();

d.demo();

d.demo(10);

}

}

Overloading Constructor• In addition to overloading normal methods,you can also overload

constructor methods

class Demo_Constructor_overload

{ Demo_Constructor_overload()

{ System.out.println("hello default constructor");

}

Demo_Constructor_overload(String s)

{ System.out.println("hello default constructor 1::"+s);

}

public static void main(String[] a1)

{ Demo_Constructor_overload d=new Demo_Constructor_overload();

Demo_Constructor_overload d1=new Demo_Constructor_overload("yugandhar");

}

}

Uses of method Overloading

• The main advantage of this is cleanliness of code.

• the use of function overloading is to save the memory space, consistency and readabiliy.

Objects as parameters to methodsclass Rectangle{ int lenght,width;

Rectangle(int lenght,int width){ this.lenght=lenght;

this.width=width;}void print_values(Rectangle r){ System.out.println("the value of member length "+r.lenght+"\n the value of member variable width is::"+this.width);}

}public class Demo_object_paramter{ public static void main(String[] y)

{ Rectangle r=new Rectangle(10,20);r.print_values(r);

}}

Objects as parameters to Constructorclass Rectangle{ int lenght,width;

Rectangle(int lenght,int width){ this.lenght=lenght;

this.width=width;}Rectangle(Rectangle r){ System.out.println("the member varialbe lenght::"+r.lenght+"\n the member varialbe height::"+r.width);}

}public class Demo_object_paramter{ public static void main(String[] y)

{ Rectangle r=new Rectangle(30,20);Rectangle r1=new Rectangle(r);

}}

Returning objects• A method can return any type of data,including class types that you create

class Rectangle

{ int length,width;

Rectangle demo(int length,int width)

{ this.length=length;

this.width=width;

return(this);

}

}

public class Demo_object_paramter

{ public static void main(String[] y)

{ Rectangle r=new Rectangle();

Rectangle r1=r.demo(30,40);

System.out.println("the value of length is::"+r1.length+"\n the value of width is::"+r1.width);

}

}

Recursion• Recursion is a basic programming technique you can use in Java, in which a

method calls itself to solve some problem.

• A method that uses this technique is recursive.

class Factorial

{ int fact(int n)

{ int result;

if(n==1)

return 1;

result=fact(n-1)*n;

return result;

}

}

public class Recursion_1

{ public static void main(String[] y)

{ Factorial f=new Factorial();

System.out.println("the factorial value is::"+f.fact(5));

}

}

String Class• The first thing to understand about strings is that every string you create is

actually an object of type string . Every string constant is actually a string Object.

• Eg System.out.println(“hello world”);

• The secound thing to understand about strings is that objects of type String are immutable once string objects are created ,its content can not be altered.

public class Private_AccessDemo

{ public static void main(String[] y)

{ String s=new String("yugandhar");

System.out.println("the s String is::"+s);

System.out.println("the String length::"+s.length());

String s1=new String("programmer");

System.out.println("the String concatination "+s+s1);

}

}

Declaring String Arraypublic static void main(String[] y)

{ String[] s=new String[3];//string array with 3

Scanner sc=new Scanner(System.in);//taking input at run time from user

for(int i=0;i<s.length;i++)

s[i]=sc.nextLine();

for(int i=0;i<s.length;i++)

System.out.println(" "+s[i]);

}

Some String Methodspublic class Private_AccessDemo

{ public static void main(String[] y)

{ String s="yugandhar";

System.out.println("the upper case::"+s.toUpperCase());

System.out.println("the upper case::"+s.toLowerCase());

System.out.println("the replace ::"+s.replace('a','r'));

System.out.println("the charAt ::"+s.charAt(8));

}

}

String Buffer Class• String Buffer creates the string of flexible length that can be modified in

terms content and length. We can insert characters and substrings in the middle of the string are append another string at the end.

public class Private_AccessDemo

{ public static void main(String[] y)

{ StringBuffer s=new StringBuffer("yugandhar");//StringBuffer constructor

System.out.println("the String Buffer class");

s.setCharAt(6,'x');//methods of String Buffer class

System.out.println(s);

System.out.println("the append string::"+s.append(" programmer"));

s.setLength(40);// methods of String Buffer class

System.out.println("the set length ::"+s.length());

}

}

Command line arguments• A command-line argument is the information that directly follows the

program’s name on the command line when it is excuted .

• All command line arguments are passed as strings

public static void main(String[] y)

{ System.out.println("the commandline arguments");

for(int i=0;i<y.length;i++)

System.out.println("the y["+i+"]::"+y[i]);

}

####output####

D:\softwares\java_programs>java Private_AccessDemo h e l l o w

the commandline arguments

the y[0]::h the y[1]::e the y[2]::l the y[3]::l the y[4]::o

the y[5]::w

Access Control• encapsulation provides another important attribute: access control.

• Java’s access specifiers are public, private, and protected

• 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

• 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

• protect: 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.

• 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.

Public access specifierpackage demo_package;import java.util.*;public class AccessDemo{ public void test()

{ System.out.println("Example of public access specifier"); } protected int x=200;

}D:\softwares\java_programs>javac -d . AccessDemo.java

import java.util.*;import demo_package.AccessDemo;

public class Public_AccessDemo{ public static void main(String[] y)

{ AccessDemo d=new AccessDemo();d.test();

} }

####output####D:\softwares\java_programs>javac Public_AccessDemo.javaD:\softwares\java_programs>java Public_AccessDemoExample of public access specifier

Private Access modifyerclass demo{ private int x=20;

private void demo(){ System.out.println("the value of x is::"+x);}void demo_1(){ System.out.println("the demo_1 value of x is::"+x);}

}public class Private_AccessDemo{ public static void main(String[] y)

{ demo d=new demo();System.out.println("the value of x is"+d.x);d.demo();d.demo_1();

} }####output####D:\softwares\java_programs>javac Private_AccessDemo.javaerror: x has private access in demo

System.out.println("the value of x is"+d.x);: error: demo() has private access in demo

d.demo()making the d.demo_1() above two lines as comment then following out put will getD:\softwares\java_programs>java Private_AccessDemothe demo_1 value of x is::20

Protected access specifyerimport java.util.*;

import demo_package.AccessDemo;

class demo

{ protected int x=20;

protected void demo()

{ System.out.println("the value of x is::"+x); }

}

public class Private_AccessDemo extends AccessDemo

{ public static void main(String[] y)

{ demo d=new demo(); d.x=30;

System.out.println("the value of x is "+d.x); d.demo();

/*try with this code to know the difference with out extends AccessDemo

AccessDemo a=new AccessDemo();

System.out.println(a.x);

-*/

Private_AccessDemo a=new Private_AccessDemo();

System.out.println(a.x);

}

}

D:\softwares\java_programs>java Private_AccessDemo

the value of x is 30 the value of x is::30 200

StaticVariable declaration with Static• When a variable is declared with the keyword “static”, its called a “class variable”.• All instances share the same copy of the variable. • A class variable can be accessed directly with the class, without the need to create a instance.class static_{ static String y="i am static variable";

String y1="hello_world";}public class Static_Demo{ public static void main(String[] y)

{ System.out.println("accessing static variable::"+static_.y);static_ s=new static_();s.y="hello";s.y1="H";//static_.y="done";System.out.println("accessing static variable::"+static_.y);/** here y shares the same copy*/static_ s1=new static_();System.out.println("accessing static variable::"+s1.y+"\n the value of y1::"+s1.y1);

} }

Method declaration with static• It is a method which belongs to the class and not to the object(instance)

• A static method can access only static data. It can not access non-static data (instance variables)

• A static method can call only other static methods and can not call a non-static method from it.

• A static method can be accessed directly by the class name and doesn’t need any object

• Syntax : <class-name>.<method-name>

• A static method cannot refer to “this” or “super” keywords in anyway

class static_{ int x=10;

static void demo(){ System.out.println("hellow static method");

// System.out.println("the value of x is"+x);/** static methods can call only other static methods* and other static variables only*/

//demo_1();demo_2();

}void demo_1(){ System.out.println("not static method demo_1()"); }

static void demo_2(){ System.out.println(" static method demo_2()"); }

}//classpublic class Static_Demo{ static void demo_3()

{ System.out.println("the main methods static"); }public static void main(String[] y){ System.out.println("static method");

static_.demo();demo_3();

} }####output####static methodhellow static methodstatic method demo_2()

the main methods static

Static block• The static block, is a block of statement inside a Java class that will be executed when

a class is first loaded in to the JVM.

class static_

{ int x=10;

void demo()

{ System.out.println("hellow"); }

static{ System.out.println("secound static block");

}

static{ System.out.println("first static block");

}

}

public class Static_Demo

{ public static void main(String[] y)

{ static_ s=new static_();

s.demo();

}

}

####output####

secound static block

first static block

hellow

final keyword• final is a reserved keyword in Java to restrict the user and it can be applied

to member variables, methods, class and local variables.

class Demo

{ final int INT_VARIABLE=120;

/**final variable value can not be chage */

public static void main(String[] y)

{ Demo d=new Demo();

d.INT_VARIABLE=45;

}

}

####output####

C:\Users\Yugandhar\Desktop\jsp>javac Demo.java

Demo.java:8: error: cannot assign a value to final variable INT_VARIABLE

d.INT_VARIABLE=45;

Final method• A final method cannot be overridden. Which means even though a sub

class can call the final method of parent class without any issues but it cannot override it.

class Super

{ final void demo()

{ System.out.println("hello"); }

}

class Sub_ extends Super

{ /*void demo()

{

System.out.println("hello world");

}*/

void demo_1()

{ System.out.println("hello world"); }

}

class Demo

{ public static void main(String[] y)

{ Sub_ s=new Sub_();

s.demo();

}

}

try to remove those comments to understand

####output####

C:\Users\Yugandhar\Desktop\jsp>javac Demo.java

Demo.java:11: error: demo() in Sub_ cannot override demo() in Super

C:\Users\Yugandhar\Desktop\jsp>java Demo

hello

Final class• We cannot extend a final class prevent inheritance

final class Super

{ void demo()

{ System.out.println("hello"); }

}

class Sub_ extends s

{ void demo_1()

{ System.out.println("hello world"); }

}

class Demo

{ public static void main(String[] y)

{ Sub_ s=new Sub_(); }

}

####output####

C:\Users\Yugandhar\Desktop\jsp>javac Demo.java

Demo.java:9: error: cannot inherit from final Super

class Sub_ extends Super

Uses of final keyword

• Using final to define constants

• Using final to prevent inheritance

• Using final to prevent overriding

• Using final for method arguments