You are on page 1of 38

Comparative Study(C# with JAVA)

Access Modifier

LEVEL – LEARNER
Icon Used

Overview Reference Questions Test Your Understanding

Check Your
Objective Lend A Hand Summary Knowledge

2
Overview

This session provides knowledge and


comparative study of the topic Access
Modifier ,Method Overloading, Static
Keyword, Static Method and Constructor
Overloading in C# and Java. The session will
help you understand the commonalities and
the difference in both the languages on the
topic covered.

3
Objective

After completing this session, participants will be


able to:
• Understand Access Modifier ,Method
Overloading, Static Keyword, Static Method and
Constructor Overloading in C# and Java
• Identify the similarities and dissimilarities
between Access Modifier ,Method Overloading,
Static Keyword, Static Method and Constructor
Overloading in C# and Java.

4
Check Your Understanding

Hi guy’s. You would have already learnt the concept and implementation of
Access Modifier ,Method Overloading, Static Keyword, Static Method and
Constructor Overloading in the primary language. Now lets have a recap of
what you have learnt :

• What is Access Modifier?


• What is Method Overloading?
• What is Static?
• What is Static Method?
• What is Constructor
Overloading

5
Just a Minute

1. Which of the following statements are correct about static method?


a. Static method can access only static data.
b. Static method cannot call instance method.
c. It is necessary to initialize static data.
d. Instance method can call static method and access static data.
e. this reference is passed to static method.

2. You want subclasses in any package to have access to members of a


superclass. Which is the most restrictive access that accomplishes this
objective?
a. public b. private
c. protected d. transient

6
Just a Minute

3. What is the most restrictive access modifier that will allow members of one
class to have access to members of another class in the same package or
assembly?
a. public b. abstract
c. protected d. synchronized e. default access

4. In which of the following should the methods of a class differ if they are to
be treated as overloaded methods?

1. Type of arguments
2. Return type of methods
3. Number of arguments
4. Names of methods
5. Order of arguments

7
Access Modifier in Java and C#

You can use the following access modifiers to specify the


accessibility of a type or member when you declare it.
Both Java and C# have their own Access Modifier as well few in
common

Access Modifier in Java Access Modifier in C#


 Public  Public
 Private  Private
 Protected  Protected
 Default  Internal
 Protected internal

8
Public Access Modifier in Java and C#

In both Java and C# if a class is marked as Public then any


external class can access the class.

Public type or Class member can be accessed by any other code


in the same assembly/Package or another assembly/Package
that references it.

* C# uses assembly similar to this in Java is a Package.

9
Private Access Modifier in Java and C#

In both Java and C# if a class is marked as private then no


external class can access the class.

Only code inside the same class can access the Private variable,
or call the Private method.

C# supports Struct also. Like only by code in the same struct


within the same assembly can access Private.

10
Protected Access Modifier in Java and C#

In Java and C# you just cannot make top level classes as


protected ,they must be inner classes.

Protected can be accessed only by the same class or subclasses


in other package/Assembly or any class within the
package/Assembly of the protected members' class.

11
Default Access Modifier in Java

• Java provides a default Modifier which is used when no access


modifier is present. Any class, field, method or constructor that
has no declared access modifier is accessible only by classes in
the same package.
• The default modifier cannot be used for methods, fields in an
interface
Example:1
class A
{
String mssg= “Hello";
void msg()
{
System.out.println(mssg);}
}

12
Internal Access Modifier in C#

• The Class by default is Internal ,accessed by any code in the


same assembly, but not from another assembly.
• When Members of a class are declared as internal, then they
can be accessed
 Within the class in which they are declared.
 Within the derived classes of that class available within the same
assembly.
 Outside the class within the same assembly.

Example:1
class BaseClass // internal by default
{
// Only accessible within the same assembly
internal static int x = 0;
}

13
Protected Internal Access Modifier in C#

• When Members of a class are declared as protected


internal, then they can be accessed
 Within the class in which they are declared.

 Within the derived classes of that class available


within the same assembly.

 Outside the class within the same assembly.

 Within the derived classes of that class available


outside the assembly.

14
Example : Protected Internal Access
Modifier in C#
class AccessModifier
   {
     // String Variable declared as protected internal
     protected internal string name;
     public void print()
      {
        Console.WriteLine("\nMy name is " + name);
      }
   }
  class Program
   {
     static void Main(string[] args)
      {
         AccessModifier ac = new AccessModifier();
        Console.Write("Enter your name:\t");
        // Accepting value in protected internal variable
        ac.name = Console.ReadLine();
        ac.print();
        Console.ReadLine();
      }
   }
}
15
Method Overloading in Java and C#

C# and Java allows us to define multiple Methods with the same name within
same class differing in the number , type , kind and order of arguments termed
as Method Overloading.

Overloaded Method Behaves in different ways depending on the arguments


supplied, which achieves Polymorphism.

16
Method Overloading in Java and C#

Method Overloading in Java Method Overloading in C#


class Calculation class Method_overloading
{ {
void sum(int a,int b)         public int Addition(int a, int b)
{         {
System.out.println(a+b);         int x;
}         return x=a+b;}
       public float Addition(float a, float b, float c)
int sum(int a,int b,int c)         {
{             float v;
return a+b+c;             return v = a + b+ c;}
} }
class Main_Method_overloading
public static void main(String args[]) {
{ public static void Main(string[] args)
Calculation obj=new Calculation(); {
obj.sum(10,10,10); Method_overloading mthover
int res= obj.sum(20,20); = new Method_overloading();
System.out.println(res);} Console.WriteLine("Addition of two integers:" 
} + mthover.Addition(2, 5));
} Console.WriteLine("Addition of three double type
values:" + mthover.Addition(0.40f, 0.50f, 0.60f));
}}}

17
Static Keyword in Java and C#
Static Keyword in Java Static Keyword in C#
• static keyword can be applied with nested • A static class is never instantiated. In the
class. static keyword can not be applied static class, we access members directly on
on top level class. the type. This eliminates misuse of the class.

• static keyword can be applied with • static keyword can be applied with variable,
variable, method. method, properties, constructor.

• A nested static class can have non-static • A static class cannot have non-static
members. All methods, fields and members. All methods, fields and properties
properties need not to be static. in it must also be static.

• When a variable is declared static ,used to • When a field is declared as static then that
refer the common property of all objects, field will exists only one copy for any number
static variable gets memory only once in of instances of the class. Hence static fields
class are at the time of class loading are used to store the data that is to be shared
by all instances of the class

18
Example : Static Keyword in Java and C#
Static Keyword in Java Static Class and Members in C#
public class NestedStaticExample static class Shape
{ {
public static void main(String args[]) public static string message;    
{  public static double GetArea(double Width,
StaticNested nested = new StaticNested(); double height)
        nested.name();     {
  }         return Width * Height;
      }
    //static nested class in java }
private static class StaticNested class Ractangle
{ {
   public void name()     private void GetRactangleArea() {
{         double Area;
    System.out.println("static nested class         Area = Shape.GetArea(10, 5);
example in java");     }
    } }
  } class Program
} {
static void Main() {
Shape.message=“This is a Rectangle”;
Console.WriteLine(Shape.message);
}}

19
Static Method in Java and C#

Static method in Java and C# have almost similar nature and


behavior. Few of the facts about static method is listed below
Static Method in Java Static Method in C#
• A static method can be accessed without • Static methods have no instances. They are
creating an instance of the class. Static called with the Class name. They are slightly
methods belong to class and not to object faster than instance methods because of
this.
• You can not use non-static variable inside a
static method • Static methods cannot access non-static class
level members
• Static method can not be overridden in
Java • Static method can not be overridden in .NET

• Static method can be public ,private and • Static method can be public ,private and
protected protected

20
Constructor in Java and C#
A constructor looks more like a method but without return type. The advantage
of constructors over methods is that they are called implicitly whenever an
object is created.
Programmer uses constructor to initialize variables, instantiating objects
Both Java and C# have constructors as class member, and are implemented in
similar fashion.

Constructor in Java Constructor in C#


 Default Constructor  Default Constructor
 Parameterized Constructor  Parameterized Constructor
 Private Constructor  Private Constructor
 Copy Constructor
 Static Constructor

21
Constructor overloading in Java and C#

Just like method overloading, constructors also can be overloaded. Same


constructor declared with different parameters in the same class is known as
constructor overloading.
Compiler differentiates which constructor is to be called depending upon the
number of parameters and their sequence of data types.
The concept of constructor overloading is same in both Java and C#

22
Example : Constructor overloading in Java
and C#
Constructor overloading in Java Constructor overloading in C#
class Student{ class Student{
int id; int id;
String name; String name;
int age; int age;
Student(int i,String n){ Student(int i,String n){
id = i; id = i;
name = n; name = n;
} }
Student(int i,String n,int a){ Student(int i,String n,int a){
id = i; id = i;
name = n; name = n;
age=a; age=a;
} }
void display(){System.out.println(id+" void display()
"+name+" "+age);} {Console.WriteLine(id+" "+name+" "+age);
}
public static void main(String args[])
{ public static void Main(String args[]){
Student s1 = new Student(111,“SAM"); Student s1 = new Student(111,“SAM");
Student s2 = new Student s2 = new
Student(222,"Anni",25); Student(222,"Anni",25);
s1.display(); s1.display();
s2.display(); s2.display();
} }
} }

23
Lend a Hand

 Create a class and members with different access modifier and try to access
in some other class in JAVA

 What is the Copy constructor in C#? Implement an example.

 Create a class with static and non-static members both fields and methods
C#
 Create a class with static and non-static members both fields and methods in
JAVA

 Create a class with static constructor in C#.

24
Lend a Hand Solution

//Create a class and members with different access modifier and try to access in some other class in JAVA
class Vehicle
{
// Instance fields
int noOfTyres; // no of tyres
private boolean accessories; // check if accessorees present or not
protected String brand; // Brand of the car
// Static fields
private static int counter;
// No of Vehicle objects created
// Constructor
Vehicle()
{
System.out.println("Constructor of the Super class called");
noOfTyres = 5;
accessories = true;
brand = "X";
counter++;
}
// Instance methods
public void switchOn() {
accessories = true;
}

25
Lend a Hand Solution

public void switchOff() {


accessories = false;
}
public boolean isPresent() {
return accessories;
}
private void getBrand() {
System.out.println("Vehicle Brand: " + brand);
}
// Static methods
public static void getNoOfVehicles() {
System.out.println("Number of Vehicles: " + counter);
}
}

class Car extends Vehicle {

private int carNo = 10;


public void printCarInfo() {
System.out.println("Car number: " + carNo);
System.out.println("No of Tyres: " + noOfTyres);
// Inherited.
// System.out.println("accessories: " + accessories); // Not Inherited.

26
Lend a Hand Solution

System.out.println("accessories: " + isPresent()); // Inherited.


// System.out.println("Brand: " + getBrand()); // Not Inherited.
System.out.println("Brand: " + brand); // Inherited.
// System.out.println("Counter: " + counter); // Not Inherited.
getNoOfVehicles(); // Inherited.
}
}

public class VehicleDetails


{

public static void main(String[] args)


{
new Car().printCarInfo();
}
}
//Output
Constructor of the Super class called
Car number: 10
No of Tyres: 5
accessories: true
Brand: X
Number of Vehicles: 1
27
Lend a Hand

//What is the Copy constructor in C#? Implement an example.


Copy Constructor : A parameterized constructor that contains a parameter of same class type is
called as copy constructor. Main purpose of copy constructor is to initialize new instance to the
values of an existing instance

Eaxmple:1
class Person
{
private string name;
private int age;
// Copy constructor.
public Person(Person previousPerson)
{
name = previousPerson.name;
age = previousPerson.age;
}
// Instance constructor.
public Person(string name, int age)
{
this.name = name;
this.age = age;
}

28
Lend a Hand

// Get accessor
public string Details
{
get { return name + " is " + age.ToString(); }
}
}

class TestPerson
{
static void Main()
{
// Create a new person object.
Person person1 = new Person("George", 40);

// Create another new object, copying person1.


Person person2 = new Person(person1);
System.Console.WriteLine(person2.Details);
}
}

//Output
George is 40

29
Lend a Hand solution

//Create a class with static and non-static members both fields and methods C#
using System;
namespace staticDemo
{
    class TestClass
  {
        public static int i;
        public static void StaticDisplay()
    {
            i=10;
            Console.WriteLine(“Value from StaticDisplay Method:”+i);
    }
        public void  NonStaticDisplay()
    {
            int j=20;
            Console.WriteLine(“Value from NonStaticDisplay Method:”+j);
    }
        static void Main(string[] args) //Output
    { Value from StaticDisplay
            TestClass obj = new  TestClass(); Method: 10
            TestClass. StaticDisplay(); Value from NonStaticDisplay
           obj. NonStaticDisplay(); Method:20
            Console.Read();
    }
  }
30}
Lend a Hand solution

//Create a class with static and non-static members both fields and methods in JAVA
    class TestClass
  {
        public static int i;
        public static void StaticDisplay()
    {
            i=10;
            System.out.println(“Value from StaticDisplay Method:”+i);
    }
        public void  NonStaticDisplay()
    {
            int j=20;
            System.out.println(“Value from NonStaticDisplay Method:”+j);
    }
        static void main(string[] args)
    {
            TestClass obj = new  TestClass();
            TestClass. StaticDisplay(); //Output
           obj. NonStaticDisplay(); Value from StaticDisplay
            Console.Read(); Method: 10
    } Value from NonStaticDisplay
  } Method:20

31
Lend a Hand solution

//Create a class with static constructor in C#.


Using System;
namespace ConstructorDemo
{
public class Bus
{
// Static constructor:
static Bus()
{
System.Console.WriteLine("The static constructor invoked.");
}
public static void Drive()
{
System.Console.WriteLine("The Drive method invoked.");
}
}
class TestBus
{
static void Main()
//Output
{
Bus.Drive(); The static constructor invoked.
} The Drive method invoked.
}
}

32
Best Practices : Object Casting in C#

• Don't overload method which accept same number of parameter with


similar types

• If you explicitly define a constructor that does take arguments


it is a good practice to always also explicitly define a constructor
that takes none unless you specifically want to exclude a constructor
with this signature, because once you explicitly define a constructor
the compiler no longer includes the default constructor in its
compiled output for you

• Do not use static and non static synchronized method to protect a


shared resource because both method locked on different object,
which means they can be executed concurrently.

33
Questions

34
Summary

 Both Java and C# supports some common access


Modifier – Public, private and protected

 Static method in Java and C#.NET have almost similar


nature and behavior. Static class in C# and nested Static
class Java

 The Concept of Method Overloading in Java and C# is


similar

 The Concept of Constructor Overloading in Java


and C# is similar, only the types of constructor vary

35
Source

• http://msdn.microsoft.com/en-us/library/ms173121.aspx
• http://www.javatpoint.com/access-modifiers
• http://msdn.microsoft.com/en-us/library/79b3xss3(v=vs.80).aspx
• http://msdn.microsoft.com/en-us/library/vstudio/ace5hbzh.aspx
• http://www.javatpoint.com/constructor

Disclaimer: Parts of the content of this course is based on the materials available from the Web sites and books
listed above. The materials that can be accessed from linked sites are not maintained by Cognizant Academy and
we are not responsible for the contents thereof. All trademarks, service marks, and trade names in this course are
the marks of the respective owner(s).

36
Comparative Study(C# with JAVA)

You have successfully completed –


Access modifier
Change Log

Version Changes made


Number
V1.0 Initial Version

V1.1 Slide No.


Changed By Effective Date Changes
Effected
         
         

38

You might also like