PPL Lecture7
PPL Lecture7
(Lecture 7)
Example
public class Dog {
String breed;
int age;
String color;
void barking() {
}
void hungry() {
}
void sleeping() {
}
}
Output
Passed Name is: tommy
Example:
class Data {
int data1;
int data2;
d1.data1 = 20;
Data d2 = d1;
d2.data2 = 40;
Data d3 = d2;
System.out.println("d3.data1 : "+d3.data1);
System.out.println("d3.data2 : "+d3.data2);
Method Declaration
Every time an object is created using the new () keyword, at least one
constructor is called.
Types of Constructors
There are two types of constructors in Java:
Default Constructor
A constructor is called "Default Constructor" when it doesn't have any parameter.
Syntax
<class name>(){}
Example:
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of obj
class Bike1{
//creating a default constructor
Bike1(){System.out.println("Bike is created");}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}
Example:
In this example, we have created the constructor of Student class that have two
parameters. We can have any number of parameters in the constructor.
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int I, String n) {
id = i;
name = n;
}
//method to display the values
void display (){System.out.println(id+" "+name);}
Example:
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
rollno=rollno;
name=name;
fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis1{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
To do so, we were using free () function in C language and delete() in C++. But,
in java it is performed automatically. So, java provides better memory
management.
Example: