[Go to site: main page, start]

0% found this document useful (0 votes)
18 views32 pages

Java Object Initialization Examples

The document contains multiple Java programming examples demonstrating various concepts such as object initialization, method overloading, access modifiers, inheritance, encapsulation, abstraction, and generics. Each example includes code snippets along with expected output, illustrating how to implement these concepts in Java. The document serves as a comprehensive guide for understanding fundamental Java programming principles.

Uploaded by

tharungoudthanda
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views32 pages

Java Object Initialization Examples

The document contains multiple Java programming examples demonstrating various concepts such as object initialization, method overloading, access modifiers, inheritance, encapsulation, abstraction, and generics. Each example includes code snippets along with expected output, illustrating how to implement these concepts in Java. The document serves as a comprehensive guide for understanding fundamental Java programming principles.

Uploaded by

tharungoudthanda
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1.

Write a Java Program to Initializing a Java Object


// Java Program to Demonstrate the
// use of a class with instance variable
// Class Declaration
public class Dog
{
// Instance Variables
String name;
String breed;
int age;
String color;
// Constructor Declaration of Class
public Dog(String name, String breed, int age, String color)
{
[Link] = name;
[Link] = breed;
[Link] = age;
[Link] = color;
}
// method 1
public String getName()
{
return name;
}
// method 2
public String getBreed()
{
return breed;
}
// method 3
public int getAge()
{
return age;
}
// method 4
public String getColor()
{
return color;
}
@Override public String toString()
{
return ("Name is: " + [Link]() + "\nBreed, age, and color are: " +
[Link]() + "," + [Link]() + "," + [Link]());
}
public static void main(String[] args)
{
Dog tuffy= new Dog("tuffy", "papillon", 5, "white");
[Link]([Link]());
}
}
Output -
Name is: tuffy
Breed, age, and color are: papillon,5,white

2. Write a Java program to Initialize Object by using Method/Function


// Java Program to initialize Java Object
// by using method/function
public class Geeks
{
static String name;
static float price;
static void set(String n, float p)
{
name = n;
price = p;
}

static void get()


{
[Link]("Software name is: " + name);
[Link]("Software price is: " + price);
}

public static void main(String args[])


{
[Link]("Visual studio", 0.0f);
[Link]();
}
}

Output -
Software name is: Visual studio
Software price is: 0.0

3. Write a Java program to demonstrate Variable’s local scope with


initialization
public class Test {
public void pupAge() {
int age = 0;
age = age + 7;
[Link]("Puppy age is : " + age);
}

public static void main(String args[]) {


Test test = new Test();
[Link]();
}
}
Java
Output -
Puppy age is: 7
Java

4. Write a Java Program to demonstrate Java Instance Variables


public String name;

// salary variable is visible in Employee class only.


private double salary;

// The name variable is assigned in the constructor.


public Employee (String empName) {
name = empName;
}

// The salary variable is assigned a value.


public void setSalary(double empSal) {
salary = empSal;
}

// This method prints the employee details.


public void printEmp() {
[Link]("name : " + name );
[Link]("salary :" + salary);
}

public static void main(String args[]) {


Employee empOne = new Employee("Ransika");
[Link](1000);
[Link]();
}
}
Output -
name : Ransika
salary :1000.0
Java

5. Write a Java program to demonstrate Java Class/Static Variables


import [Link].*;

public class Employee {

// salary variable is a private static variable


private static double salary;

// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";

public static void main(String args[]) {


salary = 1000;
[Link](DEPARTMENT + "average salary:" + salary);
}
}
Output -
Development average salary:1000

6. Write a Java Program to create and call a default constructor


(Example 1)
class Bike1
{
//creating a default constructor
Bike1()
{
[Link]("Bike is created");
}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}
Output -
Bike is created

7. Write a Java Program to create and call a default constructor


(Example 2)
class Student3
{
int id;
String name;
//method to display the value of id and name
void display(){[Link](id+" "+name);}

public static void main(String args[]){


//creating objects
Student3 s1=new Student3();
Student3 s2=new Student3();
//displaying values of the object
[Link]();
[Link]();
}
}
Output -
0 null

8. Write a
Java Program to demonstrate the use of the parameterized cons
tructor.
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(){[Link](id+" "+name);}

public static void main(String args[]){


//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
[Link]();
[Link]();
}
}
Output -
111 Karan
222 Aryan

9. Write a Java program to overload constructors


class Student5{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n){
id = i;
name = n;
}
//creating three arg constructor
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){[Link](id+" "+name+" "+age);}

public static void main(String args[]){


Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
[Link]();
[Link]();
}
}
Output -
111 Karan 0
222 Aryan 25

10. Write a Java program to demonstrate destructor


public class DestructorExample
{
public static void main(String[] args)
{
DestructorExample de = new DestructorExample ();
[Link]();
de = null;
[Link]();
[Link]("Inside the main() method");
}
protected void finalize()
{
[Link]("Object is destroyed by the Garbage Collector");
}
}
Output -
Object is destroyed by the Garbage Collector
Inside the main() method
Object is destroyed by the Garbage Collector

11. Write a Java program to demonstrate access modifiers


i) Default access modifier –
// default access modifier
package p1;
// Class Geek is having
// Default access modifier
class Geek
{
void display()
{
[Link]("Hello World!");
}
}

ii) Protected access modifier – (Example 1)


// protected access modifier
package p1;
// Class A
public class A {
protected void display() {
[Link]("GeeksforGeeks");
}
}

Example 2 -
// protected modifier
package p2;

// importing all classes


// in package p1
import p1.*;

// Class B is subclass of A
class B extends A {
public static void main(String args[]) {
B obj = new B();
[Link]();
}
}

i) Public access modifier – (Example 1)

// public modifier
package p1;

public class A {
public void display() {
[Link]("GeeksforGeeks");
}
}

Example 2 -
// public access modifier
package p2;

import p1.*;

class B {
public static void main(String args[]) {

A obj = new A();


[Link]();
}

12. Write a // Java Program to Implement Method Overloading


import [Link].*;

class MethodOverloadingEx
{

static int add(int a, int b)


{
return a + b;
}

static int add(int a, int b, int c)


{
return a + b + c;
}

// Main Function
public static void main(String args[])
{
[Link]("add() with 2 parameters");
// Calling function with 2 parameters
[Link](add(4, 6));

[Link]("add() with 3 parameters");


// Calling function with 3 Parameters
[Link](add(4, 6, 7));
}
}

Output -
add() with 2 parameters
10
add() with 3 parameters
17

13. Write a Java Program to implement Method Overriding:


import [Link].*;

// Base Class
class Animal
{
void eat()
{
[Link]("eat() method of base class");
[Link]("Animal is eating.");
}

// Derived Class
class Dog extends Animal
{
@Override
void eat()
{
[Link]("eat() method of derived class");
[Link]("Dog is eating.");
}

// Method to call the base class method


void eatAsAnimal()
{
[Link]();
}
}

// Driver Class
class MethodOverridingEx
{
// Main Function
public static void main(String args[])
{
Dog d1 = new Dog();
Animal a1 = new Animal();

// Calls the eat() method of Dog class


[Link]();
// Calls the eat() method of Animal class
[Link]();

// Polymorphism: Animal reference pointing to Dog object


Animal animal = new Dog();

// Calls the eat() method of Dog class


[Link]();

// To call the base class method, you need to use a Dog reference
((Dog) animal).eatAsAnimal();
}
}

Output -
eat() method of derived class
Dog is eating.
eat() method of base class
Animal is eating.
eat() method of derived class
Dog is eating.
eat() method of base class
Animal is eating.

14. Write a Java program to show working of user defined


Generic classes

// We use < > to specify Parameter type


class Test<T>
{
// An object of type T is declared
T obj;
Test(T obj) { [Link] = obj; } // constructor
public T getObject() { return [Link]; }
}

// Driver class to test above


class Main {
public static void main(String[] args)
{
// instance of Integer type
Test<Integer> iObj = new Test<Integer>(15);
[Link]([Link]());

// instance of String type


Test<String> sObj
= new Test<String>("GeeksForGeeks");
[Link]([Link]());
}
}

Output -
15
GeeksForGeeks

15. Write a Java program to show multiple type parameters in


Java Generics

// We use < > to specify Parameter type


class Test<T, U>
{
T obj1; // An object of type T
U obj2; // An object of type U

// constructor
Test(T obj1, U obj2)
{
this.obj1 = obj1;
this.obj2 = obj2;
}

// To print objects of T and U


public void print()
{
[Link](obj1);
[Link](obj2);
}
}

// Driver class to test above


class Main
{
public static void main (String[] args)
{
Test <String, Integer> obj =
new Test<String, Integer>("GfG", 15);

[Link]();
}
}

Output -
GfG
15

16. Write a Java Program to demonstrate Abstraction


// Demonstrating Abstraction in Java
abstract class Geeks
{
abstract void turnOn();
abstract void urnoff();
}

// Concrete class implementing the abstract methods


class TVRemote extends Geeks
{
@Override
void turnOn()
{
[Link](“TV is turned ON.”);
}

@Override
void urnoff()
{
[Link](“TV is turned OFF.”);
}
}

// Main class to demonstrate abstraction


public class Main
{
public static void main(String[] args)
{
Geeks remote = new TVRemote();
[Link]();
[Link](); }}

Output -
TV is turned ON.
TV is turned OFF.

17. Write a Java program to demonstrate the Encapsulation.


class Person {
// Encapsulating the name and age
// only approachable and used using
// methods defined
private String name;
private int age;

public String getName() { return name; }

public void setName(String name) { [Link] = name; }

public int getAge() { return age; }

public void setAge(int age) { [Link] = age; }


}

// Driver Class
public class Geeks {
// main function
public static void main(String[] args)
{
// person object created
Person p = new Person();
[Link]("John");
[Link](30);
// Using methods to get the values from the variables
[Link]("Name: " + [Link]());
[Link]("Age: " + [Link]());
}
}

Output -
Name: John
Age: 30

18. Write a Java program to illustrate the concept of single


inheritance
import [Link].*;
import [Link].*;
import [Link].*;

// Parent class
class One
{
public void print_geek()
{
[Link]("Geeks");
}
}

class Two extends One


{
public void print_for() { [Link]("for");
}
}
// Driver class
public class Main
{
// Main function
public static void main(String[] args)
{
Two g = new Two();
g.print_geek();
g.print_for();
g.print_geek();
}
}

Output -
Geeks
for
Geeks

19. Write a Java program to illustrate the concept of multi-level


inheritance

import [Link].*;
import [Link].*;
import [Link].*;

// Parent class One


class One
{
// Method to print "Geeks"
public void print_geek()
{
[Link]("Geeks");
}
}

// Child class Two inherits from class One


class Two extends One
{
// Method to print "for"
public void print_for()
{
[Link]("for");
}
}

// Child class Three inherits from class Two


class Three extends Two
{
// Method to print "Geeks"
public void print_lastgeek()
{
[Link]("Geeks");
}
}

// Driver class
public class Main
{
public static void main(String[] args)
{
// Creating an object of class Three
Three g = new Three();

// Calling method from class One


g.print_geek();

// Calling method from class Two


g.print_for();
// Calling method from class Three
g.print_lastgeek();
}
}

Output -
Geeks
for
Geeks

20. Write a Java program to illustrate the concept of


Hierarchical inheritance

class A
{
public void print_A()
{
[Link]("Class A");
}
}

class B extends A
{
public void print_B()
{ [Link]("Class B");
}
}

class C extends A
{
public void print_C()
{
[Link]("Class C");
}

class D extends A
{
public void print_D()
{
[Link]("Class D");
}
}
// Driver Class
public class Test
{

public static void main(String[] args)


{
B obj_B = new B();
obj_B.print_A();
obj_B.print_B();
C obj_C = new C();
obj_C.print_A();
obj_C.print_C();
D obj_D = new D();
obj_D.print_A();
obj_D.print_D();
}
}

Output -
Class A
Class B
Class A
Class C
Class A
Class D

21. Write a Java program to illustrate the concept of Multiple


inheritance (Interfaces)
import [Link].*;
import [Link].*;
import [Link].*;

interface One
{
public void print_geek();
}
interface Two
{
public void print_for();
}
interface Three extends One, Two
{
public void print_geek();
}
class Child implements Three {
@Override public void print_geek()
{
[Link]("Geeks");
}

public void print_for() { [Link]("for");


}
}

// Drived class
public class Main
{
public static void main(String[] args)
{
Child c = new Child();
c.print_geek();
c.print_for();
c.print_geek();
}
}

Output
Geeks
for
Geeks

22. Write a Java program to demonstrate Java IS-A type of


Relationship
class SolarSystem
{
}
class Earth extends SolarSystem
{
}
class Mars extends SolarSystem
{
}
public class Moon extends Earth
{
public static void main(String args[])
{
SolarSystem s = new SolarSystem();
Earth e = new Earth();
Mars m = new Mars();

[Link](s instanceof SolarSystem);


[Link](e instanceof Earth);
[Link](m instanceof SolarSystem);
}
}

Output
true
true
true

23. Write a Java program to demonstrate Inner class

class OuterClass {
int x = 10;

class InnerClass {
public int myInnerMethod() {
return x;
}
}
}

public class Main {


public static void main(String[] args) {
OuterClass myOuter = new OuterClass();
[Link] myInner = [Link] InnerClass();
[Link]([Link]());
}
}

24. Write a Java program to demonstrate static variables and


blocks

class Test
{
// static variable
static int a = m1();

// static block
static {
[Link]("Inside static block");
}

// static method
static int m1() {
[Link]("from m1");
return 20;
}

// static method(main !!)


public static void main(String[] args)
{
[Link]("Value of a : "+a);
[Link]("from main");
}
}

Output
from m1
Inside static block
Value of a : 20
from main

25. Write a Java program to demonstrate static methods

class Student {
String name;
int rollNo;

// static variable
static String cllgName;

// static counter to set unique roll no


static int counter = 0;

public Student(String name)


{
[Link] = name;

[Link] = setRollNo();
}

// getting unique rollNo


// through static variable(counter)
static int setRollNo()
{
counter++;
return counter;
}

// static method
static void setCllg(String name) { cllgName = name; }

// instance method
void getStudentInfo()
{
[Link]("name : " + [Link]);
[Link]("rollNo : " + [Link]);

// accessing static variable


[Link]("cllgName : " + cllgName);
}
}

// Driver class
public class StaticDemo {
public static void main(String[] args)
{
// calling static method
// without instantiating Student class
[Link]("XYZ");
Student s1 = new Student("Alice");
Student s2 = new Student("Bob");

[Link]();
[Link]();
}
}

Output
name : Alice
rollNo : 1
cllgName : XYZ
name : Bob
rollNo : 2
cllgName : XYZ

26. Write a Java program to demonstrate static classes

public class ExampleClass {


public static int count = 0;
public int id;

public ExampleClass() {
count++;
id = count;
}

public static void printCount() {


[Link]("Number of instances: " + count);
}

public void printId() {


[Link]("Instance ID: " + id);
}

public static void main(String[] args) {


ExampleClass e1 = new ExampleClass();
ExampleClass e2 = new ExampleClass();
ExampleClass e3 = new ExampleClass();

[Link]();
[Link]();
[Link]();

[Link]();
}
}
Output
Instance ID: 1
Instance ID: 2
Instance ID: 3
Number of instances: 3

27. Write a Java program to demonstrate super keyword with


variables

// super keyword in java example


// Base class vehicle
class Vehicle {
int maxSpeed = 120;
}
// sub class Car extending vehicle
class Car extends Vehicle {
int maxSpeed = 180;
void display()
{
// print maxSpeed of base class (vehicle)
[Link]("Maximum Speed: "+ [Link]);
}
}
// Driver Program
class Test {
public static void main(String[] args)
{
Car small = new Car();
[Link]();
}
}

Output
Maximum Speed: 120

28. Write a Java program to demonstrate super keyword with


methods
// super keyword in java example

// superclass Person
class Person {
void message()
{
[Link]("This is person class\n");
}
}
// Subclass Student
class Student extends Person {
void message()
{
[Link]("This is student class");
}
// Note that display() is
// only in Student class
void display()
{
// will invoke or call current
// class message() method
message();

// will invoke or call parent


// class message() method
[Link]();
}
}
// Driver Program
class Test {
public static void main(String args[])
{
Student s = new Student();

// calling display() of Student


[Link]();
}
}
Output
This is student class
This is person class
29. Write a Java program to demonstrate super keyword with
constructor

// Java Code to show use of super keyword with constructor


// superclass Person
class Person {
Person()
{
[Link]("Person class Constructor");
}
}
// subclass Student extending the Person class
class Student extends Person {
Student()
{
// invoke or call parent class constructor
super();

[Link]("Student class Constructor");


}
}
// Driver Program
class Test {
public static void main(String[] args)
{
Student s = new Student();
}
}

Output
Person class Constructor
Student class Constructor

30. Write a Java program to demonstrate final keyword


public class Example {
public static void main(String[] args) {
final int VALUE = 10; // declaring a final variable

[Link]("The value is: " + VALUE);


// VALUE = 20; // uncommenting this line will cause a compiler error
// [Link]("The new value is: " + VALUE);

final String MESSAGE = "Hello, world!"; // declaring a final variable


[Link](MESSAGE);

MyClass myObj = new MyClass();


[Link]();
[Link]();

// MyOtherClass extends MyClass {} // uncommenting this line will


cause a compiler error
}
}

class MyClass {
final String message = "Hello!"; // declaring a final instance variable

void printMessage() {
[Link](message);
}

void printFinalMessage() {
final String finalMessage = "Hello, final!";
[Link](finalMessage);
}
}

final class MyOtherClass { // declaring a final class


// ...
}

Output
The value is: 10
Hello, world!
Hello!
Hello, final!

31. Write a Java program to demonstrate this keyword

// Java Program to implement Java this reference


// Driver Class
public class Person {
// Fields Declared
String name;
int age;
// Constructor
Person(String name, int age)
{
[Link] = name;
[Link] = age;
}
// Getter for name
public String get_name() { return name; }
// Setter for name
public void change_name(String name)
{
[Link] = name;
}
// Method to Print the Details of the person
public void printDetails()
{
[Link]("Name: " + [Link]);
[Link]("Age: " + [Link]);
[Link]();
}
// main function
public static void main(String[] args)
{
// Objects Declared
Person first = new Person("ABC", 18);
Person second = new Person("XYZ", 22);
[Link]();
[Link]();
first.change_name("PQR");
[Link]("Name has been changed to: "
+ first.get_name());
}
}

Output
Name: ABC
Age: 18
Name: XYZ
Age: 22
Name has been changed to: PQR

Common questions

Powered by AI

In Java, the `super` keyword is used in class inheritance to refer to immediate parent class properties and methods. The `super` keyword can access methods of a superclass when those methods are overridden in a subclass, as shown when the `Student` class's `display` method invokes the overridden `message` method from `Person` class using `super.message()` . Additionally, `super` is used to call a superclass's constructor from a subclass's constructor, facilitating initialization of inherited properties before executing the subclass-specific constructor code. This is exemplified in the `Student` class constructor, where `super()` is invoked to call the `Person` superclass constructor , ensuring proper setup of inherited features.

Static variables and methods in Java are associated with the class itself rather than an instance of the class. This means they can be accessed without creating an instance of the class. In the provided `StaticDemo` example, `cllgName` is a static variable, and `setCllg` is a static method. `cllgName` is set using `Student.setCllg`, reflecting shared data across all instances of the `Student` class . Static methods and variables maintain a single copy at the class level and can be accessed via the class name, reducing memory usage and overhead since they only exist once in memory, regardless of how many objects are created .

Generic classes in Java are implemented using type parameters, enclosed in angle brackets `<>`, that specify the type of object it operates on. This allows a class to be parameterized, providing strong type checks during compile time while allowing code reusability and flexibility for multiple data types. The example shows a generic class `Test<T, U>` where objects of types `T` and `U` are used in the constructor and a printing method . Utilizing generics provides the advantage of code reusability without typecasting and allows for a stronger type-checking mechanism by the compiler, reducing runtime errors related to type inconsistency . It simplifies code maintenance and enhances readability.

Abstraction in Java is achieved through abstract classes and interfaces, hiding complex implementation details behind simple method declarations. The `Geeks` class, marked as abstract, exemplifies this by declaring two abstract methods, `turnOn` and `urnoff`, which are implemented in its subclass `TVRemote` . The main benefit of abstraction is that it reduces data complexity, allowing developers to focus on high-level operations rather than complex details. In the example, a `Geeks` reference is used to operate `TVRemote` methods, demonstrating how abstraction supports the flexible design and scalability of code by allowing different implementations to be swapped seamlessly without altering client code .

Java avoids multiple inheritance with classes to prevent ambiguity and complexity, commonly known as the 'diamond problem', where it's unclear which ancestor's implementation to inherit. As a solution, Java uses interfaces to provide a form of multiple inheritance. An interface can declare methods that any implementing class must define, allowing a single class to implement multiple interfaces. In the example provided, `interface One` and `interface Two` are both extended by `interface Three`, which is then implemented by the `Child` class . This demonstrates how a class can inherit behavior from multiple sources without ambiguity since interfaces only declare, not define, behaviors. This strategy maintains the clarity and simplicity of Java's class hierarchy .

Encapsulation improves data security by restricting direct access to an object's internal state and requiring all interaction to occur through methods, thus enforcing controlled data modification. In Java, encapsulation is implemented using access modifiers, as shown in the `Person` class example, where `name` and `age` fields are private. This means they can't be accessed directly outside the class . Access to these fields is provided through public methods like `getName`, `setName`, `getAge`, and `setAge`, which precisely control how the data is manipulated and retrieved . This ensures that data integrity is maintained since any logic or validation related to field manipulation can be encapsulated in these methods.

The `this` keyword in Java is a reference to the current object whose method or constructor is being invoked. It is significant because it resolves ambiguity between class attributes and parameters with the same name. In the `Person` class example, `this.name` and `this.age` differentiate instance variables from constructor parameters with identical names . This usage ensures that the constructor correctly assigns the parameter values to the instance variables. The `this` keyword can also be used to call other constructors in the same class and to pass the current object as an argument to methods, allowing for a cleaner and more readable code structure .

Constructor overloading allows a class to have more than one constructor with different parameter lists, enabling different ways to initialize an object. An example of constructor overloading is the class `Student5` that includes two constructors: one with two parameters (`int i, String n`) and another with three parameters (`int i, String n, int a`). Method overloading, on the other hand, occurs when multiple methods in the same class have the same name but different parameter lists. The `MethodOverloadingEx` class shows method overloading with two versions of the `add` method, one with two parameters and another with three . While constructor overloading is specific to constructors for class instantiation, method overloading is more general, enabling varied method behavior based on different argument lists.

Polymorphism in Java is exhibited through the ability of different classes to provide their specific implementations of methods that are initially defined in a base class, as seen with method overriding. In the provided example, an `Animal` class has a method `eat`, which is overridden in a derived class `Dog`, allowing `Dog` to have a specific `eat` behavior . The polymorphism is showcased when an `Animal` reference points to a `Dog` object and invokes the `eat` method. Despite the reference being of the type `Animal`, the `Dog`'s overridden `eat` method is called due to polymorphism in runtime method dispatch . This mechanism allows different object types to be treated through a common interface, enhancing code flexibility and reusability.

In Java, the `finalize` method is called by the garbage collector on an object before the object is destroyed, providing an opportunity to clean up resources. The `DestructorExample` class demonstrates this by overriding the `finalize` method to print a message when an object is destroyed . The method `System.gc()` is called to suggest garbage collection, but it's worth noting that actually calling `finalize` is up to the garbage collector's discretion. The output of the program first executes the main method, then prints the message from the finalize method, indicating the object's destruction . This shows the `finalize` method's role in resource cleanup just before an object is reclaimed by the garbage collector.

You might also like