Classes & Objects

... by Bit in Java Tutorial August 29, 2018

Java Package

In java we use packages to organize our classes and interfaces. We have two types if packages in java: built-in packages and the packages we can create (also known as user defined package).

Import Statements

import - The import keyword is used to make classes and interfaces available and accessible to the current source code, without specifying fully qualified package names.

NOTE: To import everything put

import java.util.*;

example:

import java.util.Random; //  hava Access to the class Random 
public class MyClass {
    public static void main (String args []){ // main method 
    Random rand = new Random(); // initialized class Object 
    int randnum = rand.nextInt(); // genertates random number and stores value into the variable randnum
    System.out.println(randnum); // print random number to console 
  }
}

Classes & Objects

Class - A class can be defined as a template/blueprint that describes the behavior/state that the object of its type support.

Object - An object is an instance of a class. Objects have states and behaviors.

Constructor - Java constructors are special methods that are called when an object is instantiated.

class Person{
public Person(){//Constructor
System.out.println("Person Created");
}
int age;
double weight;
String name;
void talk(){
System.out.println("Person Talking");
}
void eat(){
System.out.println("Person Eating");
}
void sleep(){
System.out.println("Person Sleeping");
  }
}
public class MyClass {
    public static void main (String args []){ // main method 
      Person personObject = new Person(); // object of the class Person 
      person.talk(); 
      person.eat();
      person.sleep();
    }
  }
}


output:
Person Created
Person Talking
Person Eating
Person Sleeping

Comments (1)

Search Here