Java Classes Tutorial Part-2
Java Classes Tutorial Part-2
Table of contents
Method Overloading
A single class can have multiple functions with same name and different parameters and different return types.
example:
class MethodOverloadDemo
{
int add(int x, int y)
{
return (x + y);
}
String add(String s1,String s2)
{
return (s1 + s2);
}
public static void main(String args[])
{
OverloadMethodDemo mod = new OverloadMethodDemo();
mod.add("abc","xyz");
mod.add(5,6);
}
}
*** always highest datatype constructors invoked first.
Toc
Access modifiers
- static
- final
static keyword
A static keyword can be used with variable and methods. Static variable/method available with the class itself. Static variables are used only with in the static methods or in static blocks.
class StaticDemo
{
static int a;
StaticDemo()
{
a = 10;
}
static void display()
{
System.out.println("a = " + a);
}
public static void main(String args[])
{
StaticDemo d = new StaticDemo();
StaticDemo.display();
}
}
class StaticDemo2
{
static int c;
StaticDemo2()
{
c++;
System.out.println("c = " + c);
}
public static void main(String args[])
{
StaticDemo ob1 = new StaticDemo();
StaticDemo ob2 = new StaticDemo();
StaticDemo ob3 = new StaticDemo();
}
}
public StaticDemo3()
{
name = null;
rno = 0;
}
public StaticDemo3(String n,int rn)
{
name = n;
rno = rn;
}
void display()
{
System.out.println("name = " + name);
System.out.println("Rno = " + rno);
System.out.println("college = " + college);
}
static void change()
{
college = "JBC";
}
public static void main(String args[])
{
StaticDemo3 ob1 = new StaticDemo3();
ob1.display();
StaticDemo3.change();
StaticDemo3 ob2 = new StaticDemo3();
ob2.display();
}
}
final keyword
final can be used with variable, methods, class
- final variable ----the values of variable can't be changed.
- final methods --- can't be redefined in child class.
- final class ---- can't be extended.
Example
public class FinalDemo
{
final float PI = 3.14f; //final varible
int r;
float ac = 0.0f;
void area(){
r = 6;
ac = PI*r*r;
}
void display()
{
System.out.println("ac = " + ac);
}
public static void main(String args[]){
FinalDemo fd = new FinalDemo();
fd.area();
fd.display();
}
}
Output
ac = 113.04
Multiple Classes
In java, one class object can be created in another class.
In the below example, Test class creating an object of class A.
--both the classes save in Test.java and run the file Test.java
//Test.java
class A
{
int a;
A ( int a)
{
this.a = a;
}
int square()
{
return (a * a);
}
}
public class Test
{
public static void main(String args[]){
A objA = new A(5); // class A object created in Test class
int x = objA.square();
System.out.print("sqare = " + x);
}
}
Comments
Post a Comment