OOP1 Unit4
OOP1 Unit4
Unit -4
Objects and Classes
• Java is an object-oriented programming language.
5
Java Class Methods
• You learned that methods are declared within a class, and that
they are used to perform certain actions:
Output
Static methods can be called without creating objects
Public methods must be called by creating objects
Access Methods With an Object
Output
The car is going as fast as it can!
Max speed is: 200
Constructors
class Bike1
{
Bike1()
{
System.out.println("Bike is created");
}
public static void main(String args[])
{
Bike1 b=new Bike1();
}
}
Output: Bike is created
class Student
{
int id;
String name;
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student s1=new Student();
Student s2=new Student();
s1.display();
s2.display();
}
}
Output:
0 null
0 null
Java Parameterized Constructor
class Student
{
int id;
String name;
Student(int i,String n)
{
id = i;
name = n;
}
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
s1.display();
s2.display();
}
}
Output:
111 Karan
222 Aryan
Constructor Overloading in Java
Output:
111 Karan 0
222 Aryan 25