Programming in JAVA- Unit2class
Programming in JAVA- Unit2class
class Student {
// data member (also instance variable)
int id;
// data member (also instance variable)
String name;
public static void main(String args[])
{
// creating an object of Student
Student s1 = new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}}
Java Methods
// run a method
Parameters are specified after the method name, inside the parentheses. You can add
as many parameters as you want, just separate them with a comma.
class OverloadingExample
{
static int add(int a,int b)
{return a+b;}
static int add(int a,int b,int c)
{return a+b+c;}
}
class DisplayOverloading
{
//adding two integer numbers
int add(int a, int b)
{
int sum = a+b;
return sum;
}
//adding three integer numbers
int add(int a, int b, int c)
{
int sum = a+b+c;
return sum;
}
}
class JavaExample
{
public static void main(String args[])
{
DisplayOverloading obj = new DisplayOverloading();
System.out.println(obj.add(10, 20));
System.out.println(obj.add(10, 20, 30));
}
}
Nesting Of Methods in Java
A nested method is a method that is defined inside another method.
class Main {
method1(){
}
method2(){
method1();
}
method3(){
method2();
}
}
//Nesting of Methods in Java
class demo {
private int m, n;
demo(int x, int y) {
m = x;
n = y;
}
int largest() {
if (m > n)
return m;
else
return n;
}
void display()
{
int large=largest();
System.out.println("The Greatest Number is : "+large);
}
}
public class nested_method {
public static void main(String args[]) {
demo o =new demo(10,20);
o.display();
}}
The this keyword in Java is a reference variable that refers to the current object.
It is used within an instance method or a constructor to access members of the current
object such as instance variables, methods, and constructors.
Syntax
this.memberName;
this.methodName();
this(parameters);
ThisExample(int a, int b) {
this.a = a;
this.b = b;
}
void display() {
System.out.println("a: " + this.a + ", b: " + this.b);
}
public static void main(String[] args) {
ThisExample obj = new ThisExample(10, 20);
obj.display();
}}
STATIC MEMBERS
Static members are those which belongs to the class and you can access these
members without instantiating the class.
Static Methods − You can create a static method by using the keyword static. Static
methods can access only static fields, methods.
To access static methods there is no need to instantiate the class, you can do it just
using the class name.
Static Fields − You can create a static field by using the keyword static.
The static fields have the same value in all the instances of the class.
These are created and initialized when the class is loaded for the first time.
Just like static methods you can access static fields using the class name