Class & Object in Java
Class & Object in Java
• Objects
• Inheritance
• Polymorphism
• Encapsulation
• Abstraction
• Instance
• Method
• Message Passing
Members.
• A class can also be a nested class.
Moreover, the million dollar question is, how you design such
software?
Here is the solution-
First, let’s do an exercise.
You can see the picture of three different breeds of dogs below.
Stop here right now! List down the differences between them.
Some of the differences you might have listed out maybe breed,
age, size, color, etc.
If you think for a minute, these differences are also some
common characteristics shared by these dogs.
These characteristics (breed, age, size, color) can form a data
members for your object.
Next, list out the common behaviors of these dogs like sleep, sit,
eat, etc. So these will be the actions of our software objects.
So far we have defined following things,
• Class – Dogs
Now, for different values of data members (breed size, age, and
color) in Java class, you will get different dog objects.
You can design any program using this OOPs approach.
Output:
Breed is: Maltese Size is:Small Age is:2 color is: white
class Rectangle
{
int length;
int width;
void insert(int l, int w)
{
length=l;
width=w;
}
void calculateArea()
{
System.out.println(length*width);
}
}
class TestRectangle1
{
public static void main(String args[])
{
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}
Example
public class A
{
void m1()
{
System.out.println("m1 in class A");
}
}
public class B extends A {
void m1() {
System.out.println("m1 in class B");
}
}
public class Test {
public static void main(String[] args)
{
B b = new B();
b.m1();
A a = new A();
a.m1();
A a2 = new B();
a2.m1();
}
}
Summary:
• Java Class is an entity that determines how Java Objects will
===================
public class Main
{
void main()
{
ClassA a1 = new ClassA();
//initialize the member data
//a1.x = 10;
// a1.y = 20;
a1.disp();
a1.add();
//another object
ClassA a2 = new ClassA();
//initialize the member data
//a2.x = 30;
// a2.y = 40;
a2.disp();
a2.add();
//
void add()
{
int sum ; //local variable
sum = this.x+this.y;
System.out.println("Sum = "+sum);
}
void disp()
{
System.out.println("x = "+x+ " y = "+y);
}