ch-2 Classes&Object
ch-2 Classes&Object
ch-2 Classes&Object
CLASSES,OBJECTS&
METHODS
class classname{
type instance_variable1;
type methodname1(parameter_list)
{
//body of mehod
}
type methodname2(argument_list)
{
//body of method
}
}
Declaring Class
6
class Box
{
double width;
double height; Instance Variable
double depth;
}
The new operator dynamically allocates memory for an object.
Abstraction
Encapsulation
Inheritance
Polymorphism
Abstraction
18
class Parent
{
String parentName;
String familyName;
}
class Child extends Parent
{
String childName;
int childAge;
void printMyName()
{
System.out.println (“My name is“+childName+” ”+familyName);
}
Polymorphism
28
Syntax:
type methodname(){
//code to be executed
methodname();//calling same method
}
Example:
void demo(){
System.out.println(“hello”);
demo();
}
Recursion Example
Syntax:
constructor()
{
//syntax
}
No argument Constructor
class Main {
int i;
private Main() {
i = 5;
System.out.println("Constructor is called");
}
public static void main(String[] args) {
Main obj = new Main();
System.out.println("Value of i: " + obj.i);
}
}
Ankit Shah
Default Constructor
Syntax:
Constructorname(){
//statements
}
Example Default Constructor
class Student
{ int rollNo;
String name;
Student ()
{ rollNo = 101;
name = "Suresh";
}
void display () {
System.out.println ("Student Roll Number is: " + rollNo);
System.out.println ("Student Name is: " + name);
}
}
class StudentDemo { public static void main(String args[])
{ Student s1 = new Student ();
System.out.println ("s1 object contains: ");
s1.display ();
Student s2 = new Student ();
System.out.println ("s2 object contains: ");
s2.display
Ankit();
Shah}}
Parameterized Constructor
Syntax:
constructor(parameters)
{
//statements
}
Parameterized Constructor
class Main {
String languages;
Main(String lang) {
languages = lang;
System.out.println(languages + " Programming
Language");
}
class demothisstatic{
static int num = 50;
public static void demo(){
System.out.println("Contents of the static
method"+this.num);
}
public static void main(String args[]){
demothisstatic.demo();
}
}
Garbage Collection
47
String :- java.lang.String
Character :- java.lang.Character
StringBuffer :- java.lang.StringBuffer
File class :- java.io