Class & Object in Java
Sun, 17 Nov 2024
Animal
is a class and tiger
is an object of Animal
class,<<modifiers>> class <<class name>> {
// Body of the class goes here
}
Keywords
that associate special meanings
to the class declaration,zero or more modifiers
,User defined
class name,Pascal Case
naming convention,fields
, methods
,Hooman.java
)public class Hooman {
...
}
public
modifier,Hooman
,field
,constructor
& some methods
,A class in Java may consist of 5
components:
attributes
of objects of that class,2
types of fields
for a class:Non-static
variables,separate copy
of these variables,accessed using object
of the class,.
),obj.name;
,Static
variables,static keyword
as a modifier,same copy
of these variables,Shared among all objects
of this class,called using class name
,.
) on both object
and class
,MyClass.count
,static
as well as non-static
fields are initialized to a default value,numeric
field (int
, long
, ...) is initialized to zero(0)
,boolean
field is initialized to false
,reference
type field is initialized to null
,behavior of objects
of the class,create objects
of the class,initializing static variables
which need some calculation
,initializing variables
which need some calculation
,this
refers to current instance
. More details is discussed next section,Hooman.java
,public class Hooman {
// Field - 2 Class variables
public static final String SPECIES;
private static int objectCounter = 0;
// Field - 3 instance variables
private String name;
private int age;
private boolean isAdult;
//static initializers - 1
static {
// normally more calculation is performed as per need
SPECIES = "Homo Sapiens";
}
//instance initializers - 1
{
isAdult = false; // by default false though
}
//constructor - 1
public Hooman() {
objectCounter++;
}
//constructor - 2
public Hooman(String name, int age) {
this.name = name;
this.age = age;
isAdult = age >= 18;
objectCounter++;
}
// methods - 6 methods
public String getName() {...}
public void setName(String name) {...}
public int getAge() {...}
...
}
behavior
of objects of the class,block of code
,<<modifiers>> <<return type>> <<method name>> (<<parameters list>>) <<throws clause>> {
// Body of the method goes here
}
Formal parameters
of a method are treated as local variables,throws
is optional,public void setAge(int age) {
if(age < 0 || age < this.age) return;
this.age = age;
isAdult = (age>=18);
}
return-type
can be any data type,void
means doesn't return any value,camelCase
naming convention,name
, andnumber
, types
,order
,Modifiers
, return-type
, and parameter names
aren't part of the signature
, public int add(int num1, int num2){
return num1+num2;
}
add(int, int)
;two types of method
like variables:Instant method
and Class method
,Non-static
method,behavior of the objects
of the class,called using object
,showSpecificCharacter()
in Hooman.java
,public void showSpecificCharacter(){
System.out.println("Name is => "+name);
}
Accessing like thisHooman anik = new Hooman("Anik",22);
anik.showSpecificCharacter(); // Name is => Anik
static
method,behavior of the class
itself,object
or Class name
(Recommended) itself,showSomeCharacter()
in Hooman.java
,public static void showSomeCharacter(){
System.out.println("General characteristics");
//System.out.println(name);//can't access instant variable here
}
Calling like thisHooman anik = new Hooman("Anik",22);
anik.showSomeCharacter(); // General characteristics -------(a)
Hooman.showSomeCharacter(); // General characteristics -----(b)
(a)
is ok but not recommended
,(b)
best practice,main()
methodpublic
,static
, void
, method name main
and having a String array
as parameter,public static void main(String[] args) {
// entry point of execution
}
JVM invokes this method
. If not found, then JVM does not know where to start the application. So, it throws an error stating that no main() method was found,main()
method in a class having different signature. But JVM will call only the above one,main()
method just like other method,Test.java
, public class Test {
public static void main(String[] args) {
...
}
...
}
Instance
method is invoked on an instance of the class
using dot(.
) notation,Class method
is invoked on Class name
using dot(.
) notation,main()
in Test.java
,Hooman anik = new Hooman("Anik",22);
anik.showSpecificCharacter(); // instance
Hooman.showSomeCharacter(); // static
initialize an object
of a class,throws
clause also):<<Modifiers>> <<Constructor Name>>(<<parameters list>>){
// Body of constructor goes here
}
number
, order
, or type
of parameters,Access modifiers
are same as others,JVM
adds a default constructor
as long as there is no constructor.default constructor
doesn't accept any parameter and does nothing,default constructor
only satisfies logic so that we can create object,static
. Remember static
is part of class not object,Bird.java
,public class Bird {
...
// constructor - 1
public Bird() {
this.name = "Unknown";
this.species = "Not found";
this.canFly = false;
}
// constructor - 2
public Bird(boolean canFly) {
this("unknown","Not found",canFly); // calling other constructor. Remember `this`. must be first line
}
// constructor - 3
public Bird(String name, String species, boolean canFly) {
this.name = name;
this.species = species;
this.canFly = canFly;
}
// constructor - 4 . Copy constructor
public Bird(Bird bird){
this.name = bird.name;
this.species = bird.species;
this.canFly = bird.canFly;
}
...
}
Creating object like this: See birdTest()
in Test.java
:private static void birdTest(){
Bird deadBird = new Bird(); // 1
deadBird.printDetails(); // Unknown -> Not found -> false
Bird unknownBird = new Bird(true); // 2
unknownBird.printDetails(); // unknown -> Not found -> true
Bird eagle = new Bird("Eagle", "Eagle", true); // 3
eagle.printDetails(); // Eagle -> Eagle -> true
Bird secondEagle = new Bird(eagle); // 4
secondEagle.printDetails(); // Eagle -> Eagle -> true
}
new Hooman();
, This object will be automatically deleted, since we are not assigning it in any variable.new
keyword, it allocates memory for each instance field
of the class,Hooman saeed = new Hooman("Saeed",21);
System.out.println(saeed.isAdult()); // true
method
, constructor
, block
,Not initialized
by default,error
instead of garbage value,LocalVariable.java
for full code,public class LocalVariable {
...
private int num; // global, value = 0
...
public void assignMust(){
int num; // local, no default value
//System.out.println(num); // error. Not initialized.
}
public int calculateDifference(int num2){
int num = 1001; // local
System.out.println(num); // 1001 since local get precedence
return this.num - num2; // this.num refers to global num
}
}
special reference type
called null type
,Assignment compatible
with any other reference
type. Ex:String name = null; // ok
Integer number = null; // ok
Hooman none = null; // ok
int count = null; // error. int is not reference type. Remember?
sh = null;
, the object sh
was referring will be destroyed by JVM, since it is no longer accessible.Hooman sh = new Hooman("sh",22);
sh = null;
current instance
of a class. (Alert it's for instance
, not class),instance/object
,TriState.java
,public class TriState {
...
private StateEnum state = StateEnum.FIRST; // will be discussed later
public TriState(StateEnum state) { // state = SECOND is passed
System.out.println(this.state); // FIRST
System.out.println(state); // SECOND
this.state = state; // this.state refers to the global state --- (a)
}
...
}
TriState triState = new TriState(SECOND);
System.out.println(triState.state); ---- (b)
triState.state
in outside is same as this.state
inside the class for a specific object of the class. See (b)
and (a)
.prevent modification
on which it is used,constant
,3
contexts:Variable
assigned
a value only once
,Can't reassign
after assigning,blank final
variable,final int total;
Class
:extended
or inherited
,Method
:redefined
(overridden
or hidden
) in the subclasses
,getArea()
of Test.java
:private static double getArea(final double r){ // final parameter
final double pi = 3.1415; // final local variable
//pi = 3; // error
//r = 5; // error
return pi*r*r;
}
final
or blank final
,Rules
apply for initializing
a blank final
instance variable:one of the instance initializers
or in all
constructors,assign value at once
. If you try to reassign it, you will get error,blank final
variables and final reference variables
are runtime constants. i.e. they are calculated at runtime,Circle.java
,public final class Circle {
public static final double PI = 3.14159; // final
private final double r; // blank - final
public Circle() {
this.r = 0;
}
public Circle(double r) {
this.r = r;
}
public Circle(Circle c){
this(c.r); // it will assign value
//this.r = c.r; // error, since already assigned in previous line
}
public double getArea(){
return PI * r * r;
}
}
capital letter
for variable naming,public static final double PI = 3.14159;
variable-length arguments
,constructor
,...
) is used,array
. But we don't have to pass array explicitly,max()
in Test.java
,private static int max(int... arr){
if(arr.length == 0) return 0;
int mx = Integer.MIN_VALUE;
for(int num : arr){
if(num > mx) mx = num;
}
return mx;
}
Using like this:System.out.println( max() ); // 0
System.out.println( max(1,22) ); // 22
System.out.println( max(1,2,3,4,5,6,7,8,10) ); // 10
2
restriction:maximum one varargs
,// n1 has infinite length, so n2 is not needed. error
void m1(String str, int...n1, int...n2) {
...
}
must be the last argument
in the argument-list. Same reason even though parameter type is different.void m2(int...n1, String str) {
...
}
This is perfectly valid: See findMinMax()
Test.java
,private static int findMinMax(boolean findMax, int ...arr){...}
true polymorphic
code(Works for any types),public class Wrapper<T> {
// Code for the Wrapper class goes here
}
T
is a type variable
. It can be of any type, but must be reference type,MyList.java
,public class MyList <T>{
private final List<T> list = new ArrayList<>();
public MyList() {}
public void add(T item){
list.add(item);
}
public T get(int index) throws ArrayIndexOutOfBoundsException{...}
}
Using like this: See simpleGenericTest()
in Test.java
,private static void simpleGenericTest(){
MyList<Integer> myList = new MyList<>();
//MyList myList = new MyList<>(); // ok but not recommended.
myList.add(12);
myList.add(32);
myList.add(42);
myList.add(62);
//System.out.println( myList.get(5) ); // Index out of bound
System.out.println( myList.get(1) ); // 32
}
This is a comment 1.
This is a comment 2.